是的你可以. (很抱歉回答我自己的问题,我认为这是一个有趣的解决方案)
我在幻灯片#12上找到了代码示例的大纲.
我已经在/实现了这一点(仍处于测试阶段)
在创建新版本时,您必须使用脚本URL的版本控制来刷新缓存,但这适用于具有localStorage的页面,并且在localStorage不可用时也可以使用.我在页脚中添加了一些调试代码,以显示js的加载位置.
我把它分成了一个标题和一个页脚的脚本.这些内联显示.
在标题中(我把它放在这里,因为我们使用modernizr将一些类添加到html标记中,我希望那些尽可能快地用于渲染目的.可以移动到页脚.
// .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();
}
};
并在页脚中(出于性能原因).我放置标准加载方法.请注意,只要您设置了过期标头,使用此分支的浏览器都会正确缓存.
// 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('
loaded from server and not stored');
}
else if (!_mob_load_js) {
// add a note to the footer
document.write('
loaded via ajax and stored in localStorage');
}
else {
// add a note to the footer
document.write('
loaded from localStorage');
}
我已经在chrome和safari中确认js是从localStorage加载的,并且站点功能按预期工作,并且没有向服务器发出请求.我已经确认,当在IE或Firefox上运行时,它会加载脚注中的脚本.
注意:我添加了代码来包装try catch中的evals,因为我在firefox中遇到了问题.
如果觉得《iphone html5 浏览器缓存文件 如何使用html5 localStorage在iphone Safari上缓存javascript?...》对你有帮助,请点赞、收藏,并留下你的观点哦!