开发者

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 wit开发者_StackOverflow社区h 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?


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.


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


I had a similar question and also created a small library for that. 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 functionality that I need. You can check my code at Github, I'm sure you'll be able to understand all of it quite fast. But if you just want to go ahead and use it here is a full example how to use it.

The complete 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)};

Calling the library

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜