JavaScript How to avoid caching and dynamic load of stylesheets

Sometimes you can to have problem that is in your changed stylesheets are not applied to the page. What's the matter you ask. I tell that it is because browsers can cache your css and instead of loading load them from server again, it returns stylesheet from cache.

Short code, that will allow you to avoid caching of your CSS, also Js applies to the script. The idea is that to add new GET parameter after the address of the stylesheet, that will be unique. It made the page not to cache stylesheet and get it from server time to time. Come generating algorithm is not necessary, I simply used Date object for this.

      function loadStyleSheets(stylelist)
{
var head = $$("head")[0];
var date = new Date();
var dateString = Date.parse(date.toString());
for(var i = 0; i < stylelist.length; i++)
{
var link = document.createElement("link");
link.href="style/" + styleList[i] + "?" + dateString;
link.type = "text/css";
link.rel = "stylesheet";
head.appendChild(link);
}
}

date.toString() returns string representation of Date like 'Mon Sep 28 14:36:22 GMT-0700 1998'. Be sure to not use it as a parameter of get that's why this kind of line do we translate by Date.parse() function into the numeric form.

In the script I use $$ from prototype library. It returns an array of DOM elements in the structure of page with the name specified in the parameter. On the assumption that the elements head on, and then only one appeal on the ground to the first element. If anything is a small thought loadable styles through js, say to use different skins.

Comments

Are you human

You can use simple HTML-formatting tags(like <b>, <ul>, <code> and others)

Are you human
IzzyMenu
Wow free space!
search engine optimization
Wow free space!
Advertise on this site