一.LocalStorage
1.用于永久性的进行本地缓存,不会自动清除、没有过期时间,直至手动清除数据。
2.LocalStorage采用的是键值对的方式进行存储,存储方式只能是字符串。存储内容可以用图片、json、样式、脚本等。
示例代码:
<script>
//通过localStorage直接引用key, 另一种写法,等价于:
//localStorage.getItem("pageLoadCount");
//localStorage.setItem("pageLoadCount", value);
if (!localStorage.pageLoadCount)
localStorage.pageLoadCount = 0;
localStorage.pageLoadCount = parseInt(localStorage.pageLoadCount) + 1;
document.getElementById('count').textContent = localStorage.pageLoadCount;
</script>
<p>
You have viewed this page
<span id="count">an untold number of</span>
time(s).
</p>
二.sessionStorage
1.SessionStorage用于本地存储一个会话中的数据,这些数据只有在同一个会话中的页面才能访问并且会话结束,窗口关闭后,数据就会消失。
2.是一种会话级别的存储。
示例代码:
<script>
// 当页面刷新时,从sessionStorage恢复之前输入的内容
window.onload = function(){
if (window.sessionStorage) {
var name = window.sessionStorage.getItem("name");
if (name != "" || name != null){
document.getElementById("name").value = name;
}
}
};
// 将数据保存到sessionStorage对象中
function saveToStorage() {
if (window.sessionStorage) {
var name = document.getElementById("name").value;
window.sessionStorage.setItem("name", name);
window.location.href="session_storage.html";
}
}
</script>
<form action="./session_storage.html">
<input type="text" name="name" id="name"/>
<input type="button" value="Save" onclick="saveToStorage()"/>
</form>
三.webstorage
1.webStorage的数据只能进行本地存储,不能向服务器进行传递。
2.没有时间有效期。
示例代码:
<script>
if(window.openDatabase){
//打开数据库,如果没有则创建
var db = openDatabase('mydb', '1.0', 'Test DB', 2 * 1024);
//通过事务,创建一个表,并添加两条记录
db.transaction(function (tx) {
tx.executeSql('CREATE TABLE IF NOT EXISTS LOGS (id unique, log)');
tx.executeSql('INSERT INTO LOGS (id, log) VALUES (1, "foobar")');
tx.executeSql('INSERT INTO LOGS (id, log) VALUES (2, "logmsg")');
});
//查询表中所有记录,并展示出来
db.transaction(function (tx) {
tx.executeSql('SELECT * FROM LOGS', [], function (tx, results) {
var len = results.rows.length, i;
msg = "<p>Found rows: " + len + "</p>";
for(i=0; i<len; i++){
msg += "<p>" + results.rows.item(i).log + "</p>";
}
document.querySelector('#status').innerHTML = msg;
}, null);
});
}
</script>
四.离线缓存
1.离线浏览 用户可在应用离线时使用它们。
2. 已缓存资源加载速度更快。
3.减少了服务器负载,浏览器将只从服务器下载更新过或更改过的资源。
示例代码:
<html manifest="demo_html.appcache">
<body>
<script src="demo_time.js"></script>
<p id="timePara"><button onclick="getDateTime()">Get Date and Time</button></p>
<p><img src="img_logo.gif" width="336" height="69"></p>
<p>Try opening <a href="tryhtml5_html_manifest.htm" target="_blank">this page</a>, then go offline, and reload the page. The script and the image should still work.</p>
</body>
</html>