项目中需要将在线的Web改造成支持离线版本的Web应用,思考了四种方法:
1.Manifest文件
它的特点有以下三点:
1.1 Manifest文件有变化才有更新
1.2一次必须更新完Manifest中的所有文件
1.3更新完成后下次生效
操作方式如下:
1.在html的开始标签中,我们指定一个.manifest文件
<html lang="en" man[ifest="/offline.manifest">
2.由于manifest文件的MIME类型为text/cache-manifest,因此需要在服务器端配置:
1.apache服务器需要在mime.types中加入以下配置:text/cache-manifestmaifest。或者可以在.htacess中加入以下配置 AddType text/cache-manifest.maifest。
<span style="font-size:14px;color:#666666;">CACHE MANIFEST
#v1
CACHE:
basic_page_layout_ch4.html
css/main.css
img/atwiNavBg.png
NETWORK:
*
FALLBACK:
//offline.html</span>
属性:
NETWORK:部分罗列了所有不需要被缓存的文件,你可以将看成一个”在线白名单“。此处罗罗列的文件在网络畅通的情况下都会直接跳过缓存。如果你想网络内容在网络畅通个的情况下及时更新,可以在此处使用* 。星号呗成为在线白名单通配符。
FALLBACK:部分使用/字符定义了一个URL模板,他的作用是访问每个页面时都会问”缓存中有这个页面吗?“如果有则显示缓存页面,如果没有,则显示指定的offline.html文件。
2.Local storage
local storage的特点是永久存储,也就是持久化本地存储的表现。
2.1.接口与事件
它采用键值对的数据存储方式,完全以字符串的形式存储。
localStorage.getItem(key),用于获取指定key本地存储的值。
localStorage.setItem(key,value),该接口用于将value的值村吃到key字段中。
localStorage.removeItem(key),用于删除指定key在本地存储的值。
localStorage.length
localStorage.key(index),用于返回指定的key。
localStorage.clear().用于清除所有的本地存储
3.SessionStorage
该方法的接口和事件与localStorage是一样的,不同的是它是会话级别的数据,当关闭了页面之后,这些数据就会被删除。
4.Web SQL
该方法是web端的数据库方法,用于存储一些具有复杂数据结构的数据形式和以上几种无法存储的文件等。
考虑到数据类型的不同,主要采取以下方法进行存储:
主页使用 第一种格式存储。
CSS样式、js动作,样本文件js,内容js采用localstorage存储。
复杂数据格式采取Web SQL存储。
代码如下:
<script type="text/javascript">
$(document).ready(function () {
console.log('ready %o',new Date());
var APP_START_FAILED = "I'm sorry, the app can't start right now.";
function startWithResources(resources, storeResources) {
// Try to execute the Javascript
try {
//eval(resources.js); v6
insertScript(resources.js);
setTimeout(function(){
APP.applicationController.start(resources, storeResources);
},500);
// If the Javascript fails to launch, stop execution!
} catch (e) {
alert(APP_START_FAILED);
console.log('%o',e);
}
}
function startWithOnlineResources(resources) {
startWithResources(resources, true);
}
function startWithOfflineResources() {
var resources;
// If we have resources saved from a previous visit, use them
if (localStorage && localStorage.resources) {
resources = JSON.parse(localStorage.resources);
startWithResources(resources, false);
// Otherwise, apologize and let the user know
} else {
alert(APP_START_FAILED);
}
}
// If we know the device is offline, don't try to load new resources
if (navigator && navigator.onLine === false) {
startWithOfflineResources();
// Otherwise, download resources, eval them, if successful push them into local storage.
} else {
$.ajax({
url: 'api/resources/',
success: startWithOnlineResources,
error: startWithOfflineResources,
dataType: 'json'
});
}
function insertScript (script) {
var node=document.createElement('script');
node.innerHTML=script;
document.head.appendChild(node);
}
});
</script>