Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you cache javascript on iphone Safari using html5 localStorage?

I am building a mobile website that uses the main jquery library and some js of our own. Our website is too big and has too much data to be a simple offline/online web app. We need web connectivity.

I'm trying to improve caching performance for caching a large amount of javascript for a mobile site. It is well known that that caching on the iPhone's safari is limited to files 15-25kb in size, and our minified js is around 125kb.

I've thought about using the cache manifest, but this has the disadvantage that the browser requests the cache-manifest with each page load, and since we aren't using a single page web app, this adds additional requests to the server.

Can we cache the javascript in localStorage (available in mobile safari and on the android browser) and then execute it from there?

like image 958
Sean Avatar asked Feb 24 '11 17:02

Sean


2 Answers

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

I found an outline of a code example here on slide #12.

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

I've implemented this on http://m.bbref.com/ (still in beta)

You have to use versioning of the script url to flush the cache when a new version is created, but this works for pages with localStorage and will also work when localStorage is not available. I've added some debugging code to the footer to show you where the js is loading from.

I've split this into a script for the header and one of the footer. These appear inline.

In the header (I've put it here as we use modernizr to add some classes to the html tag and I want those there as quickly as possible for rendering purposes. Could be moved to 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 place the standard loading method. Note that the browsers that use this branch all cache properly so long as you have expires headers set.

<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've confirmed in chrome and safari that the js is loaded from localStorage and the site functionality works as expected, and there is no request made to the server. And I've confirmed that when running on IE or firefox it loads the script as found in the footer.

Note: I added code to wrap the evals in try catch since I was having a problem in firefox.

like image 75
Sean Avatar answered Sep 20 '22 04:09

Sean


Also, I also came across this script loader called basket.js, it might do exactly what you are wanting.

like image 24
meme Avatar answered Sep 21 '22 04:09

meme