How to cache javascript on iphone Safari using html5 localStorage?

I am creating a mobile website that uses the main jquery library and some native js. Our website is too large and contains too much data to be a simple standalone / online application. We need a network connection.

I am trying to improve the caching performance for caching a lot of javascript for a mobile site. It is well known that caching on iPhone safari is limited by the file size of 15-25kB, and our mini-js are about 125KB.

I was thinking about using a cache manifest, but this has the disadvantage that the browser requests a cache manifest every time the page loads, and since we are not using a single-page web application, this adds additional requests to the server.

Is it possible to cache javascript in localStorage (available in mobile safari and in the Android browser) and then execute it from there?

+7
source share
3 answers

Yes, you can. (sorry for answering my own question, I thought this was an interesting solution)

I found a sample code diagram here on slide # 12.

http://www.slideshare.net/jedisct1/abusing-javascript-to-speedup-mobile-web-sites

I implemented this at http://m.bbref.com/ (still in beta)

You need to use the script url version to clear the cache when creating the new version, but this works for pages with localStorage and will also work if localStorage is not available. I have added debugging code in the footer to show you where js is loading from.

I split it into a script for the header and one of the footer. They appear on the line.

In the header (I added it here when we use modernizr to add some classes to the html tag, and I want them there as quickly as possible for rendering purposes. It can be moved to the footer.

<script type="text/javascript"> // .001 is the current js version // this script assumes it is in the root web directory. var js_file = "site_lib.001.js"; // vars to store where the file is loaded from. var _mob_load_js = false; var _mob_ajax_load_js = false; { // if we have localStorage and the files exists there get it. if(window.localStorage && window.localStorage[js_file]) { // eval the js file. try{ window.eval(window.localStorage[js_file]); // successfully eval'ed the code, so // we don't need to download it later. _mob_load_js = true; } catch (e) { _mob_load_js = false; } } else if (window.localStorage) { // We have localStorage, but no cached file, so we // load the file via ajax, eval it and then store // the file in localStorage // To remove previous versions, I remove all of our localStorage, // This is extreme if we store other vars there. window.localStorage.clear(); // standard ajax request. var xhr = new XMLHttpRequest(); xhr.onreadystatechange = function() { if (xhr.readyState == 4) { // eval the js try { window.eval(xhr.responseText); // successfully eval'ed the code, so // we don't need to download it later. _mob_ajax_load_js = true; } catch (e) { _mob_ajax_load_js = false; } try { // store the js. window.localStorage[js_file] = xhr.responseText; } catch (e) {} } else { return; } }; xhr.open("GET",js_file,true); xhr.send(); } }; </script> 

and in the footer (for performance reasons). I put the standard boot method. Note that browsers that use this branch will cache completely until you run out of headers.

 <div id="sr_external_script"></div> <script type="text/javascript"> // We haven't loaded the js yet, so we create a script // tag and get the script the old fashioned way if (!_mob_load_js && !_mob_ajax_load_js) { var script=document.createElement("script"); script.type="text/javascript"; script.src=js_file; document.getElementById("sr_external_script").appendChild(script); // add a note to the footer document.write('<div>loaded from server and not stored</div>'); } else if (!_mob_load_js) { // add a note to the footer document.write('<div>loaded via ajax and stored in localStorage</div>'); } else { // add a note to the footer document.write('<div>loaded from localStorage</div>'); } </script> 

I confirmed in chrome and safari that js is loading from localStorage, and the functionality of the site works as expected, and the server does not receive a request. And I confirmed that when working in IE or firefox, it loads the script as shown in the footer.

Note. I added code to wrap evals in a try catch since I am having a problem with firefox.

+18
source

In addition, I also came across this script loader called basket.js , it can do exactly what you want.

+2
source

I had a similar question, and a small library was created for this. You can find it at https://github.com/webpgr/cached-webpgr.js

I created it since basket.js has some dependency and provided much more features that I need. You can check my code on Github, I'm sure you can figure it all out pretty quickly. But if you just want to go further and use it here, this 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'); }); 
0
source

All Articles