javascript - How to force browser to reload cached CSS/JS files? -


i have noticed browsers (in particular, firefox , opera) zealous in using cached copies of .css , .js files, between browser sessions. leads problem when update 1 of these files user's browser keeps on using cached copy.

the question is: elegant way of forcing user's browser reload file when has changed?

ideally solution not force browser reload file on every visit page. post own solution answer, curious if has better solution , i'll let votes decide.

update:

after allowing discussion here while, have found john millikin , da5id's suggestion useful. turns out there term this: auto-versioning.

i have posted new answer below combination of original solution , john's suggestion.

another idea suggested scdf append bogus query string file. (some python code automatically use timestamp bogus query string submitted pi.). however, there discussion whether or not browser cache file query string. (remember, want browser cache file , use on future visits. want fetch file again when has changed.)

since not clear happens bogus query string, not accepting answer.

update: rewritten incorporate suggestions john millikin , da5id. solution written in php, should adapted other languages.

update 2: incorporating comments nick johnson original .htaccess regex can cause problems files json-1.3.js. solution rewrite if there 10 digits @ end. (because 10 digits covers timestamps 9/9/2001 11/20/2286.)

first, use following rewrite rule in .htaccess:

rewriteengine on rewriterule ^(.*)\.[\d]{10}\.(css|js)$ $1.$2 [l] 

now, write following php function:

/**  *  given file, i.e. /css/base.css, replaces string containing  *  file's mtime, i.e. /css/base.1221534296.css.  *    *  @param $file  file loaded.  must absolute path (i.e.  *                starting 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); } 

now, wherever include css, change this:

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

to this:

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

this way, never have modify link tag again, , user see latest css. browser able cache css file, when make changes css browser see new url, won't use cached copy.

this can work images, favicons, , javascript. not dynamically generated.


Comments

Popular posts from this blog

angular - Ionic slides - dynamically add slides before and after -

minify - Minimizing css files -

Add a dynamic header in angular 2 http provider -