[Beginner] Busting cache on file links


(Nic Hubbard) #1

We have problems with file assets such as PDF files being cached and users don't clear their browser cache, etc etc, so they get the old version of the file. This is a frustrating problem, so I whipped up this small cache busting script to fix the issue. The script adds a random string to the end of the file url, which will help with the caching issue:

/**
* Busts the cache for file assets
*
* @param string url The url to add the random string to
*
* @version $Revision: 0.1
*/
function fileCacheBuster(url) {

// If we have already added, don’t do it again
if (url.indexOf(‘zscb=’) != -1) {
return url;
}

// Min and max
var mx = 99999999;
var mn = 1;

// Create the random number
var r = Math.floor(Math.random() * (mx - mn + 1)) + mn;

// Apply the random string
if (url.indexOf(’?’) != -1) {
return url+’&zscb=’+r;
} else {
return url+’?zscb=’+r;
}

}//end

 

The script can then be used like (using jQuery):

 

$("a[href*='.pdf'], a[href*='.doc'], a[href*='.xls'], a[href*='.ppt']").click(function() {
   var url = $(this).attr('href');
   $(this).attr('href', fileCacheBuster(url));
});

 


(Robin Shi) #2

Hi Nic,

This script is to uncache the files and your server is quite strong to handle the requests. Just wondering how you set up the infrastructure?

Thanks.

Robin


(Nic Hubbard) #3

Hi Nic,

This script is to uncache the files and your server is quite strong to handle the requests. Just wondering how you set up the infrastructure?

Thanks.

Robin

 

I didn't say it was a good idea for everyone. :)