最近被問到你會離線緩存嗎,一頭霧水,所以決定自己寫一個demo來驗證一些,
準備工作:把demo放到了nginx服務器中跑起來,啟動服務器(start nginx)
配置manifest文件
在html標簽加上manifest屬性 <html manifest="index.manifest">
項目根目錄下的./index.manifest文件內容如下
<pre>CACHE MANIFEST </pre>
<pre>#version 1 </pre>
<pre>#CACHE:其后列出的是需要緩存的內容 </pre>
<pre>CACHE:
index.html
img/u-img.jpg</pre>
<pre>#NETWORK:其后列出的是不進行緩存的內容,每次都需要從服務器端獲取 </pre>
<pre>NETWORK:
FALLBACK:
404.html
</pre>
<pre>
//強制檢查服務器上的manifest文件是否有更新
window.applicationCache.update();
</pre>
<i>
chrome console報錯如下:
Uncaught DOMException: Failed to execute 'update' on 'ApplicationCache': there is no application cache to update.
<i>
<b>問題竟然是由于在manifest中圖片的路徑寫錯了,img/u-img.png寫成了img/u-img.jpg 導致不能離線緩存
當manifest中配置的文件正確時,
you able to see some files in Chrome's web dev tools under Resource->Application Cache.
</b>
當你停掉(nginx.exe -s stop 或 nginx.exe -s quit)服務器時,被緩存的文件img/u-img.png能正確顯示,其他圖片不能正確加載。
==============================================
離線緩存一些講解
一、緩存狀態(tài):window.applicationCache 對象是對瀏覽器的應用緩存的編程訪問方式。其 status 屬性可用于查看緩存的當前狀態(tài)。
applicationCache.status的值如下:
0 === 未緩存
1 === 空閑(緩存為最新狀態(tài))
2 === 檢查中
3 === 下載中
4 === 更新就緒
5 === 緩存過期
主動更新緩存:applicationCache.update()
<pre>
<script>
//利用定時器隔一定時間自動更新一下緩存
setInterval(function(){ applicationCache.update(); },50000);
</script>
</pre>
二、介紹一下緩存相關的事件。
1、updateready事件:當有新的緩存,并更新完以后,會觸發(fā)此事件。
例如代碼:
<pre>
applicationCache.addEventListener("updateready",function(){ alert("緩存更新完成");},false);
</pre>
2、progress事件:當有新的緩存,并處于正在下載的過程中時,會不斷觸發(fā)此事件。progress中的event對象包含:loaded和total。loaded代表當前已經加載完成的文件,total為總共需要更新的文件數。
<pre>
applicationCache.addEventListener("progress",function(){
alert(applicationCache.status); // 3表示正在下載
},false);
</pre>
3、其他事件:
checking事件:正在檢查
downloading事件:正在下載
updatereadey事件:更新完成
obsolete事件:緩存過期
cached事件:空閑,緩存為最新狀態(tài)
error事件:報錯
noupdate事件:檢查更新結束,沒有需要更新。