JavaScript file caching

What is the best way to force the browser to use cached versions of js files (from servers)?

+49
javascript caching
Nov 22 '08 at 8:05
source share
8 answers
+20
Nov 23 '08 at 16:42
source share

or in the .htaccess file

AddOutputFilter DEFLATE css js ExpiresActive On ExpiresByType application/x-javascript A2592000 
+20
Nov 22 '08 at 8:28
source share

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 MYH:i:s', time()+$expires).'GMT'); ob_end_flush(); return; } 

works for me.

As a developer, you are likely to quickly come across a situation where you do not want to cache files, in which case, see Help with aggressive JavaScript caching

+6
Nov 22 '08 at 8:14
source share

I just finished a weekend project cached-webpgr.js which uses localStorage / web storage to cache JavaScript files. This approach is very quick. My little test showed

  • Download jQuery from CDN: Chrome 268ms , FireFox: 200 ms
  • Download jQuery from localStorage: Chrome 47 ms , FireFox 14 ms

The code for this is tiny, you can check it in my Github project https://github.com/webpgr/cached-webpgr.js

Here is a complete example of how to use it.

Full library:

 function _cacheScript(c,d,e){var a=new XMLHttpRequest;a.onreadystatechange=function(){4==a.readyState&&(200==a.status?localStorage.setItem(c,JSON.stringify({content:a.responseText,version:d})):console.warn("error loading "+e))};a.open("GET",e,!0);a.send()}function _loadScript(c,d,e,a){var b=document.createElement("script");b.readyState?b.onreadystatechange=function(){if("loaded"==b.readyState||"complete"==b.readyState)b.onreadystatechange=null,_cacheScript(d,e,c),a&&a()}:b.onload=function(){_cacheScript(d,e,c);a&&a()};b.setAttribute("src",c);document.getElementsByTagName("head")[0].appendChild(b)}function _injectScript(c,d,e,a){var b=document.createElement("script");b.type="text/javascript";c=JSON.parse(c);var f=document.createTextNode(c.content);b.appendChild(f);document.getElementsByTagName("head")[0].appendChild(b);c.version!=e&&localStorage.removeItem(d);a&&a()}function requireScript(c,d,e,a){var b=localStorage.getItem(c);null==b?_loadScript(e,c,d,a):_injectScript(b,c,d,a)}; 

Library call

 requireScript('jquery', '1.11.2', 'http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js', function(){ requireScript('examplejs', '0.0.3', 'example.js'); }); 
+6
Mar 08 '15 at 2:36
source share

In the Apache.htaccess file:

 #Create filter to match files you want to cache <Files *.js> Header add "Cache-Control" "max-age=604800" </Files> 

I also wrote about it here:

http://betterexplained.com/articles/how-to-optimize-your-site-with-http-caching/

+4
Nov 22 '08 at 8:32
source share

I am very tempted to close this as a duplicate; this question is likely to be answered differently throughout the site:

  • will the script in the html script tag with php extension be cached?
  • When does the browser automatically clear the cache of an external JavaScript file?
  • Aggressive JavaScript Caching Help
  • How to manage web page caching in all browsers?
  • How to make browser see CSS and Javascript changes?
+2
Nov 22 '08 at 8:32
source share

The best (and only) method is to set the correct HTTP headers, in particular the following: Expire, Last Modified, and Cache Control. How to do this depends on the server software you are using.

In Improving performance ... find “Server Side Optimization” for general considerations and related links and for “client side cache” for Apache-specific advice.

If you are a fan of nginx (or nginx in plain English ), like me, you can also easily configure it:

 location /images { ... expires 4h; } 

In the above example, any file from / images / will be cached on the client for 4 hours.

Now that you know the right words to search (HTTP headers "Expires", "Last-Modified" and "Cache-Control"), just browse the documentation of your web server.

0
Nov 26 '08 at 17:05
source share

I have a simple system that is pure JavaScript. It checks for changes in a simple text file that is never cached. When you download a new version, this file changes. Just put the next JS at the top of the page.

  (function(url, storageName) { var fromStorage = localStorage.getItem(storageName); var fullUrl = url + "?rand=" + (Math.floor(Math.random() * 100000000)); getUrl(function(fromUrl) { // first load if (!fromStorage) { localStorage.setItem(storageName, fromUrl); return; } // old file if (fromStorage === fromUrl) { return; } // files updated localStorage.setItem(storageName, fromUrl); location.reload(true); }); function getUrl(fn) { var xmlhttp = new XMLHttpRequest(); xmlhttp.open("GET", fullUrl, true); xmlhttp.send(); xmlhttp.onreadystatechange = function() { if (xmlhttp.readyState === XMLHttpRequest.DONE) { if (xmlhttp.status === 200 || xmlhttp.status === 2) { fn(xmlhttp.responseText); } else if (xmlhttp.status === 400) { throw 'unable to load file for cache check ' + url; } else { throw 'unable to load file for cache check ' + url; } } }; } ; })("version.txt", "version"); 

just replace the version.txt file with your file that always runs, and the "version" with the name that you want to use for local storage.

0
Sep 17 '16 at 21:06
source share



All Articles