views:

2220

answers:

6

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
+6  A: 

or in the .htaccess file

AddOutputFilter DEFLATE css js
ExpiresActive On
ExpiresByType application/x-javascript A2592000
William Macdonald
+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
+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
A: 
Eugene Lazutkin