Which is the best method to make the browser use cached versions of js files (from the serverside)?
+2
A:
From PHP:
function OutputJs($Content)
{
ob_start();
echo $Content;
$expires = DAY_IN_S; // 60 * 60 * 24 ... defined elsewhere
header("Content-type: x-javascript");
header('Content-Length: ' . ob_get_length());
header('Cache-Control: max-age='.$expires.', must-revalidate');
header('Pragma: public');
header('Expires: '. gmdate('D, d M Y H:i:s', time()+$expires).'GMT');
ob_end_flush();
return;
}
works for me.
As a developer you'll probably quickly run into the situation that you don't want files cached, in which case see Help with aggressive JavaScript caching
Ken
2008-11-22 08:14:37
+6
A:
or in the .htaccess file
AddOutputFilter DEFLATE css js
ExpiresActive On
ExpiresByType application/x-javascript A2592000
William Macdonald
2008-11-22 08:28:04
+3
A:
I am heavily tempted to close this as a duplicate, this question appears to be answered in many different ways all over the site:
- http://stackoverflow.com/questions/301284/will-a-script-in-htmls-script-tag-with-extension-php-be-cached
- http://stackoverflow.com/questions/206783/when-does-browser-automatically-clear-javascript-cache
- http://stackoverflow.com/questions/54475/help-with-aggressive-javascript-caching
- http://stackoverflow.com/questions/49547/making-sure-a-web-page-is-not-cached-across-all-browsers
- http://stackoverflow.com/questions/3224/how-can-i-make-the-browser-see-css-and-javascript-changes
Kent Fredric
2008-11-22 08:32:30
Seems like a good candidate for a general communitywiki question then? It is obviously an itch that lots of people need scratched.
Ken
2008-11-22 08:35:36
+1
A:
In your Apache .htaccess file:
#Create filter to match files you want to cache
<Files *.js>
Header add "Cache-Control" "max-age=604800"
</Files>
I wrote about it here also:
http://betterexplained.com/articles/how-to-optimize-your-site-with-http-caching/
kurious
2008-11-22 08:32:47
+4
A:
Have a look at Yahoo! tips: http://developer.yahoo.com/performance/rules.html#expires.
There are also tips by Google: http://code.google.com/speed/page-speed/docs/caching.html
powtac
2008-11-23 16:42:04
A:
Eugene Lazutkin
2008-11-26 17:05:25