標籤:des blog http java 使用 io strong 檔案 資料
什麼是應用程式緩衝(Application Cache)?
HTML5 引入了應用程式緩衝,這意味著 web 應用可進行緩衝,並可在沒有網際網路串連時進行訪問。
應用程式緩衝為應用帶來三個優勢:
離線瀏覽 - 使用者可在應用離線時使用它們
速度 - 已緩衝資源載入得更快
減少伺服器負載 - 瀏覽器將只從伺服器下載更新過或更改過的資源。
瀏覽器支援
所有主流瀏覽器均支援應用程式緩衝,除了 Internet Explorer。
Cache Manifest 基礎
如需啟用應用程式緩衝,請在文檔的 <html> 標籤中包含 manifest 屬性:
Java代碼
- <!DOCTYPE HTML>
- <html manifest="demo.appcache">
- ...
- </html>
每個指定了 manifest 的頁面在使用者對其訪問時都會被緩衝。如果未指定 manifest 屬性,則頁面不會被緩衝(除非在 manifest 檔案中直接指定了該頁面)。
manifest 檔案的建議的副檔名是:".appcache"。
請注意,manifest 檔案需要配置正確的 MIME-type,即 "text/cache-manifest"。必須在 網頁伺服器上進行配置。
Manifest 檔案
manifest 檔案是簡單的文字檔,它告知瀏覽器被緩衝的內容(以及不緩衝的內容)。
manifest 檔案可分為三個部分:
CACHE MANIFEST - 在此標題下列出的檔案將在首次下載後進行緩衝
NETWORK - 在此標題下列出的檔案需要與伺服器的串連,且不會被緩衝
FALLBACK - 在此標題下列出的檔案規定當頁面無法訪問時的回退頁面(比如 404 頁面)
上述資料copy自http://www.w3school.com.cn/html5/html_5_app_cache.asp
下面貼一下我自己操作的流程:
1、web容器配置。Application Cache的核心是manifest 檔案,要載入manifest 檔案,就要先讓web容易認識這個東東,所以要先配置MIME-type 映射。我用的是tomcat容器,找到conf/web.xml檔案,在那一大堆<mime-mapping>後面加上manifest配置
Java代碼
- <!--html5 mime-type setting -->
- <mime-mapping>
- <extension>manifest</extension>
- <mime-type>text/cache-manifest</mime-type>
- </mime-mapping>
- <!--html5 mime-type setting -->
,儲存重啟,完成第一步。
2、編寫manifest檔案。我的manifest檔案為cache/demo.appcache,內容入下:
Java代碼
- CACHE MANIFEST
- # 2012-11-01 v1.0.0
- ../image/baidu_sylogo1.gif
-
- NETWORK:
- ../image/cat.gif
-
- FALLBACK:
- 404.html
3、html使用manifest檔案。
Java代碼
- <!DOCTYPE>
- <html manifest="../cache/demo.appcache">
- <head>
- <title>test4.html</title>
- <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
- <meta http-equiv="description" content="this is my page">
- <meta http-equiv="content-type" content="text/html; charset=UTF-8">
- </head>
- <body>
- <div>
- <img alt="aaa" src="../image/baidu_sylogo1.gif" >
- <img id="msg" alt="bbb" src="" >
- <script type="text/javascript">
- var msg=document.getElementById("msg");
- msg.src=‘../image/cat.gif‘;
- </script>
- </div>
- </body>
- </html>
baidu_sylogo1.gif為緩衝,而cat.gif是直接從伺服器讀取。
4、測試。筆者用chrome測試了一下正常顯示,firefox也OK。不過PC上看不出啥來(比較明顯的是manifest 檔案中的路徑配置錯誤,debug模式會報錯,正常的情況下瀏覽器會提示是否使用xxx網站提供的待用資料),我用我自己的手機測試了一下,效果比較明顯(WI-FI壞境下)。重新整理頁面的速度很快,關閉WI-FI時,重新刷頁面,可以看到第一個圖片,而第二個圖片顯示不出來。
FROM :http://xiaofengyu.iteye.com/blog/1711518
HTML 5 學習之應用程式緩衝