Cache busting document links with jQuery

Cache-busting is the process by which a page content is served in such a manner as to prevent the element to be served from a browser or proxy cache. It prevents the browser or proxy from reusing an element it has already loaded and cached and forces it to always fetch the file from the server. (source : digitalmarketing-glossary.com)

In a recent project that I was working on, I had to apply cache busting technique to certain parts of the application. The below code modifies the links within a container that has a class uncache and adds a timestamp to it. Hope this is helpful to readers.

Thus a link

<a href="http://www.nadzweb.com/hello" class="uncache">Hello</a>

becomes

<a href="http://www.nadzweb.com/hello?cb=9087654322" class="uncache">Hello</a>
/** add cache to anchors that have 'uncache' class **/
$('.container a.uncache').each(function(index) {
    var obj_uncache = $(this);
    var uncached_link = obj_uncache.attr('href') + '?cb='+ new Date().getTime();
    obj_uncache.attr('href', uncached_link);
});
One Comment

Add a Comment

Your email address will not be published. Required fields are marked *

*
To prove you're a person (not a spam script), type the security word shown in the picture. Click on the picture to hear an audio file of the word.
Anti-spam image