HTML5离线储存
warning:
这篇文章距离上次修改已过203天,其中的内容可能已经有所变动。
HTML5提供了两种机制来实现离线存储:本地存储(LocalStorage)和sessionStorage,以及应用程序缓存。
- 本地存储(LocalStorage)
LocalStorage 接口用于 long-term 存储数据(没有时间限制的数据存储)。在所有同源窗口中,数据都是可以共享的。
<!DOCTYPE html>
<html>
<body>
<p>Click button to save data to local storage:</p>
<button onclick="saveData()">Save Data</button>
<button onclick="readData()">Read Data</button>
<script>
function saveData() {
localStorage.setItem("key", "value");
console.log(localStorage.getItem("key"));
}
function readData() {
console.log(localStorage.getItem("key"));
}
</script>
</body>
</html>
- 应用程序缓存(AppCache)
应用程序缓存是一种旧的离线存储技术,它允许你缓存你的web应用,使其离线可用。
<!DOCTYPE html>
<html manifest="example.appcache">
...
</html>
在example.appcache文件中:
CACHE MANIFEST
# 2019-04-23 v1.0.0
CACHE:
example.html
style.css
script.js
NETWORK:
*
FALLBACK:
/offline.html
- sessionStorage
sessionStorage 是 LocalStorage 的一个简化版,它与 LocalStorage 的工作方式相同,但数据只在当前会话期间有效,关闭页面即消失。
<!DOCTYPE html>
<html>
<body>
<p>Click button to save data to session storage:</p>
<button onclick="saveData()">Save Data</button>
<button onclick="readData()">Read Data</button>
<script>
function saveData() {
sessionStorage.setItem("key", "value");
console.log(sessionStorage.getItem("key"));
}
function readData() {
console.log(sessionStorage.getItem("key"));
}
</script>
</body>
</html>
以上就是HTML5的离线存储的几种方式,你可以根据你的需求选择合适的方式。
评论已关闭