How to Rotate Your Banner Bypass Cache using JavaScript

Website or WordPress caching usually make it hard to make an area of your site to be dynamic. Caching time out sometime take 30 minutes to 1 hour to refresh the site content unless you choose to clear or flush the cache manually. Couple of days ago, i was looking for a solution to rotate my banner images using PHP but the cache from WordPress Super Cache did not allow this.

The cache from WordPress Super Cache will cache the first banner images from rotate and it will stay the same and will refresh again after cache time out about 3600 seconds or 1 hour. This is not what i’m intended to do so digging further, i look into JavaScript solution and luckily i’ve found one.

In this tutorial, i will show you how to use JavaScript to rotate your banner and advertisement embed code bypass any cache from plugin or website config.

Step 1 – Create a rotate.js

First create an empty JavaScript file and name it rotate.js

Step 2 – Insert JS Code

Copy paste below JS Code into the newly created rotate.js and save the JS file.

[code lang=”js”]/* random rotate function */
function rand(min, max) {
var offset = min;
var range = (max – min) + 1;
var randomNumber = Math.floor( Math.random() * range) + offset;
return randomNumber;

function MyCustomAds() {
var ad1 = ‘this is html or code for ad1’;
var ad2 = ‘this is html or code for ad2’;
var ad3 = ‘this is html or code for ad3’;
var ad4 = ‘this is html or code for ad4’;
var ad5 = ‘this is html or code for ad5’;

var items = Array(ad1,ad2,ad3,ad4,ad5);
randomNumber = rand(0, items.length – 1);
randomAd = items[randomNumber];

/* choose one of the ad and echo it */

Step 3 – Add The Javascript in HTML Header

Open you Website HTML or WordPress header.php and add this before closing of </head>
[code lang=”js”]<script src="" type="text/javascript"></script>[/code]
Replace the domain/path to the actual path location of your rotate.js

Step 4 – Add to HTML or Template file

Finally all you have to do is to add this code anywhere in your HTML or WordPress Template.
[code lang=”js”]<script type="text/javascript">MyCustomAds();</script> [/code]

Final Result

Now, even with caching active, the banner will rotate randomly and dynamically without losing the effective of content caching for your other area in site.

Source: Photo Credit

Scroll to Top