DIV CSS 佈局教程網

用 JavaScript localStorage 打造本地快取的完整做法
編輯:關於JavaScript     

為什麼要用 localStorage 做本地快取

在瀏覽器端保存資料的方式有很多,早期我們多半依賴 Cookie,但它每次請求都會跟著送到伺服器,容量也有限。HTML5 帶來的 window.localStorage 則提供了一個更清爽的選擇:資料長期保存在使用者本機,除非手動清除,否則不會過期消失。下面的範例示範了如何把輸入框的內容寫入 localStorage,並在頁面載入時讀回;同時也保留了 Cookie 作為舊瀏覽器的後備方案。

完整示例程式碼

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <title>本地緩存</title>
    <script type="text/javascript">
        var strKey = "strKey";
        var storage = window.localStorage;

        function onStart(){
            if(storage.getItem(strKey)!=null){
                alert(storage.getItem(strKey)+'localStorage');
            }else if(Cookie.read(strKey)!=null){
                alert(Cookie.read(strKey)+'cookie');
            }
        }

        function bendihuancun(){
            var strValue = document.getElementById("username").value;
            if (storage) {
                storage.setItem(strKey, strValue);
            } else {
                Cookie.write(strKey, strValue);
            }
        }
    </script>
  </head>
  <body onload="onStart()">
    <input type="text" id="username" value="123">
    <input type="button" value="保存緩存" onclick="bendihuancun()">
  </body>
</html>

運作流程說明

頁面載入時會觸發 onStart(),它先嘗試從 localStorage 取出對應的鍵值;若取不到,再退而檢查 Cookie 是否存有舊資料。點擊「保存緩存」按鈕則會呼叫 bendihuancun(),把輸入框的值透過 setItem 寫入。整個邏輯以「優先使用 localStorage,能力不足時改用 Cookie」為核心,讓程式在各種環境下都能平穩運作。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved