I\'d like to append a random string to an element\'s attribute, using either jQuery or javascript.
I need to reference a CSS f
Adding a random string is called a cache-buster. You shouldn't do it on every page load as it completely defeats the purpose of cache.
To answer how to accomplish it with a random string, you can try this:
$('<link/>').attr({
type: 'text/css',
rel: 'stylesheet',
href: 'http://example.com/style.css?' + randString(4)
}).appendTo('head');
Here's a simple random string generator function:
/**
* Function generates a random string for use in unique IDs, etc
*
* @param <int> n - The length of the string
*/
function randString(n)
{
if(!n)
{
n = 5;
}
var text = '';
var possible = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
for(var i=0; i < n; i++)
{
text += possible.charAt(Math.floor(Math.random() * possible.length));
}
return text;
}
Keep it simple, apply the current timestamp in miliseconds to the URL:
// this fellow creates a link to the style sheet
// after the page has loaded
var link = $("<link>");
link.attr({
type: 'text/css',
rel: 'stylesheet',
href: 'http://example.com/style.css?' + (new Date).getTime()
});
$("head").append( link );
Please note that this is really a bad idea, if you're not going to change your stylesheet much, just replace the URL manually in the files. There are tools for that purpose available (sed
under Linux-based systems)
You can get just part of the date, for example:
var d = new Date;
// this string will change once a day for the same user
var rnd_str_day = d.getFullYear() + '_' + d.getMonth() + '_' + d.getDay();
href= 'http://example.com/style.css?' + rnd_str_day;
// this string will change once an hour
var rnd_str_hour = d.getFullYear() + '_' + d.getMonth() + '_' + d.getDay() + '_' + d.getHours();
href= 'http://example.com/style.css?' + rnd_str_hour;
And so the css will be uncached once a day or an hour, depending on your requeriments.