繁体   English   中英

如何使用html5 localStorage在iPhone Safari上缓存JavaScript?

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

我正在建立一个使用主要jquery库和我们自己的js的移动网站。 我们的网站太大,数据太多,无法成为简单的离线/在线Web应用程序。 我们需要Web连接。

我正在尝试提高缓存性能,以便为移动网站缓存大量的javascript。 众所周知,在iPhone的safari中缓存仅限于15-25kb的文件,而我们的精简版js约为125kb。

我已经考虑过使用缓存清单,但是这样做的缺点是浏览器会在每次页面加载时请求缓存清单,并且由于我们没有使用单个页面的Web应用程序,因此会向服务器添加其他请求。

我们可以将javascript缓存在localStorage中(可在移动Safari和Android浏览器中使用),然后从那里执行它吗?

是的你可以。 (很抱歉回答我自己的问题,我认为这是一个有趣的解决方案)

我在幻灯片#12上找到了代码示例的概述。

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

我已经在http://m.bbref.com/上实现了此功能(仍处于测试版)

创建新版本时,必须使用脚本URL的版本控制来刷新缓存,但这适用于具有localStorage的页面,并且在localStorage不可用时也可以使用。 我在页脚中添加了一些调试代码,以向您展示js的加载位置。

我将其拆分为用于页眉和页脚之一的脚本。 这些显示为内联。

在页眉中(我已经将其放在此处,因为我们使用modernizr向html标签添加了一些类,并且我希望这些类能尽快出现在此处以进行渲染。可以移至页脚。

<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>

和在页脚中(出于性能原因)。 我放置了标准加载方法。 请注意,只要您设置了过期标题,使用该分支的浏览器都将正确缓存。

<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>

我已经在chrome和safari中确认了js是从localStorage加载的,并且站点功能按预期工作,并且没有对服务器发出任何请求。 而且我已经确认,在IE或firefox上运行时,它会加载页脚中的脚本。

注意:由于在Firefox中遇到问题,我添加了代码以将eval包装在try catch中。

另外,我还遇到了一个名为basket.js的脚本加载器,它可能完全满足您的要求。

我有一个类似的问题,并为此创建了一个小型图书馆。 您可以在https://github.com/webpgr/cached-webpgr.js上找到它

我创建它是因为basket.js具有一定的依赖性,并提供了我需要的更多功能。 您可以在Github上查看我的代码,我相信您将能够很快理解所有代码。 但是,如果您只是想继续使用它,这里是如何使用它的完整示例。

完整的库:

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

调用图书馆

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');
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM