|

Evitar el caché en las hojas de estilo

Algo que suele ocurrir con frecuencia es que al realizar cambios en la hoja de estilos, estos no se vean reflejados en la página por el caché del navegador.

Para evitar esto, tan solo es necesario un script que cargue los estilos y que le añada un parámetro GET que sea único para que el navegador lo entienda como un fichero nuevo. En este caso el parámetro es la fecha.

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);
}
}

En este caso el autor hace uso de la función de Prototype $$, pero se podría hacer sin el uso de este framework.

Como consejos sobre el mismo tema yo añadiría dos:

  • si estás trabajando en local y no ves los cambios, carga en el navegador directamente el fichero .css que hayas modificado, así los cambios aparecerán, luego los podrás ver en la página.
  • si la página se crea mediante PHP le puedes añadir a la etiqueta link el parametro GET directamente:
<link rel="stylesheet" href="estilos.css?refresh=<?php echo time(); ?>" />

How to avoid caching and dynamic load of stylesheets