客戶端存儲數(shù)據(jù)
- 兩種方式:
- localStorage-沒有時間限制的數(shù)據(jù)存儲
- 存儲特點: localStorage方法存儲的數(shù)據(jù)沒有時間限制。第二天,第二周或下一年之后,數(shù)據(jù)依然可用。
- sessionStorage-針對一個session的數(shù)據(jù)存儲
- 存儲特點: sessionStorage方法針對一個session進行數(shù)據(jù)存儲,用戶關(guān)閉瀏覽器后,數(shù)據(jù)會被刪除
- 與cookie做對比:
之前,這些都是由cookie完成的。但是cookie不適合大量數(shù)據(jù)的存儲,因為它們由每個對服務(wù)器的請求來傳遞,這使得cookie速度很慢而且效率也不高
代碼示例
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<textarea name="" id="ta" cols="30" rows="10"></textarea>
<button id="btn">save</button>
<script>
var ta=document.querySelector('#ta'),
btn=document.querySelector('#btn');
if(localStorage.text){
ta.value=localStorage.text;
}
btn.onclick=function(){
localStorage.text=ta.value;
}
</script>
</body>
</html>
應(yīng)用緩存
- 什么是應(yīng)用程序緩存:
HTML5引入了應(yīng)用程序緩存,這意味著web應(yīng)用可進行緩存,并可在沒有因特網(wǎng)連接時進行訪問 - 應(yīng)用緩存的優(yōu)勢:
- 離線瀏覽-用戶可在應(yīng)用離線時使用它們
- 速度-已緩存資源加載得更快
- 減少服務(wù)器負載-瀏覽器將只從服務(wù)器下載更新過或更改過的資源
- 實現(xiàn)緩存:
如需應(yīng)用程序緩存,請在文檔的<html>標簽中包含manifest屬性
manifest文件的建議的文件擴展名是:".appcache" - Manifest 文件:
- CACHE MANIFEST-在此標題下列出的文件將在首次下載后進行緩存
- NETWORK-在此標題下列出的文件需要與服務(wù)器的連接,且不會被緩存
- FALLBACK-在此標題下列出的文件規(guī)定當頁面無法訪問時的回退頁面(比如404頁面)
代碼示例:
創(chuàng)建文件為:index.html
<!DOCTYPE html>
<html manifest="index.appcache">
<head lang="en">
<meta charset="UTF-8">
<title></title>
<link href="style.css" rel="stylesheet" type="text/css">
</head>
<body>
<h1 class="h1">Hello HTML5!</h1>
</body>
</html>
接下來創(chuàng)建文件為:index.appcache
CACHE MANIFEST
CACHE:
index.html
index.js
NETWORK:
style.css
用chrome打開index.html后檢查元素就會發(fā)現(xiàn)index.html index.js緩存下來了,而style.css沒有緩存。
web workers
- 什么是Web Worker?
web worker是運行在后臺的JavaScript,獨立于其他腳本,不會影響頁面的性能 - 方法:
postMessage()-它用于向HTML頁面?zhèn)骰匾欢蜗?br> terminate()-終止web worker,并釋放瀏覽器/計算機資源 - 事件:
onmessage
代碼示例
創(chuàng)建主文件:index.html
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
<script src="index.js"></script>
</head>
<body>
<div id="numDiv">0</div>
<button id="start">start</button>
<button id="stop">stop</button>
</body>
</html>
創(chuàng)建:index.js
var numDiv;
var work = null;
window.onload = function(){
numDiv = document.getElementById("numDiv");
document.getElementById("start").onclick = startWorker;
document.getElementById("stop").onclick = function(){
if(work){
work.terminate();
work = null;
}
}
}
function startWorker(){
if(work){
return;
}
work = new Worker("count.js");
work.onmessage = function(e){
numDiv.innerHTML = e.data;
}
}
最后創(chuàng)建:count.js
var countNum = 0;
function count(){
postMessage(countNum);
countNum++;
setTimeout(count,1000);
}
count();