in Web and Tech

CSS Hack: Detect an updated CSS (or JS or image files) and override cached version

Discussion of original solution is here:
https://stackoverflow.com/questions/118884/how-to-force-the-browser-to-reload-cached-css-js-files

The rewrite rule in htaccess:

RewriteEngine on
RewriteRule ^(.*)\.[\d]{10}\.(css|js)$ $1.$2 [L]

The PHP function:

/**
 *  Given a file, i.e. /css/base.css, replaces it with a string containing the
 *  file's mtime, i.e. /css/base.1221534296.css.
 *  
 *  @param $file  The file to be loaded.  Must be an absolute path (i.e.
 *                starting with slash).
 */
function auto_version($file)
{
  if(strpos($file, '/') !== 0 || !file_exists($_SERVER['DOCUMENT_ROOT'] . $file))
    return $file;

  $mtime = filemtime($_SERVER['DOCUMENT_ROOT'] . $file);
  return preg_replace('{\\.([^./]+)$}', ".$mtime.\$1", $file);
}

The implementation:

Instead of:

<link rel="stylesheet" href="/css/base.css" type="text/css" />

Rewrite it such that the href value is passed on to the function, like so:

<link rel="stylesheet" href="<?php echo auto_version('/css/base.css'); ?>" type="text/css" />

Write a Comment

Comment