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'); });
select Mar 08 '15 at 2:36 2015-03-08 14:36
source share