web端存儲的幾種方式


1、userdata存儲,只適用於ie,每個頁面只能存儲64kb,該域名網站最多存儲640kb;

userdata重點使用語法:

UserData.o = document.createElement('input');
UserData.o.type = "hidden";
UserData.o.style.behavior = "url('#default#userData')" ;
//上面三條是創建節點;
UserData.o.load(name);//讀取指定文件name
UserData.o.setAttribute("key", val);//將數據存儲到這個節點;
UserData.o.save(name);//存儲這個文件名,方便查找
復制代碼
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<script type="text/javascript">  
/** @class 定義userdata的操作 */   
    var UserData = {   
        // 定義userdata對象   
        o : null,   
        // 設置文件過期時間   
        defExps : 365,   
        // 初始化userdate對象   
        init : function(){   
            if(!UserData.o){   
                try{   
                    //創建userData存儲  
                    UserData.o = document.createElement('input');   
                    UserData.o.type = "hidden";   
                    UserData.o.style.behavior = "url('#default#userData')" ;   
                    // UserData.o.addBehavior ("#default#userData");   
                    document.body.appendChild(UserData.o);   
                }catch(e){   
                    return false;   
                }   
            };   
                return true;   
        },   
        // 保存文件到userdata文件夾中 f-文件名,c-文件內容,e-過期時間   
        save : function(f, c, e){   
            if(UserData.init()){   
                var o = UserData.o;   
                // 保持對象的一致   
                o.load(f);   
                // 將傳入的內容當作屬性存儲   
                if(c) o.setAttribute("code", c);   
                // 設置文件過期時間   
                var d = new Date(), e = (arguments.length == 3) ? e : UserData.defExps;   
                d.setDate(d.getDate()+e);   
                alert(d);  
                o.expires = d.toUTCString();   
                // 存儲為制定的文件名   
                o.save(f);   
            }   
        },   
        // 從uerdata文件夾中讀取指定文件,並以字符串形式返回。f-文件名   
        load : function(f){   
            if(UserData.init()){   
                var o = UserData.o;   
                // 讀取文件   
                o.load(f);   
                // 返回文件內容   
                return o.getAttribute("code");   
            }   
        },   
        // 檢查userdata文件是否存在 f-文件名   
        exist : function(f){   
            return UserData.load(f) != null;   
        },   
        // 刪除userdata文件夾中的指定文件 f-文件名   
        remove : function(f){   
            UserData.save(f, false, -UserData.defExps);   
        }   
        // UserData函數定義結束   
    };   
    window.onload=function(){  
        var boxDom=document.getElementById("box");  
        var testPDom=document.getElementById("testP");  
        var inputDom=boxDom.getElementsByClassName("inputTxt");  
        var btnDom=document.getElementById("btn");  
        inputDom[0].onblur=function(){  
            var val=this.value;  
            if(val != null || val != ""){  
                testPDom.innerText=val;  
                UserData.save("name",val,2);  
                console.log("保存成功");  
            }  
        }  
        //都去存儲的userData數據  
        btnDom.onclick=function(){  
            alert(UserData.load("name"));  
            inputDom[0].value=UserData.load("name");  
        }  
    }  
</script>  
   
<body>  
<div id="box">  
    <input type="text" class="inputTxt">  
    <button type="button" id="btn">保存</button>  
</div>  
<p id="testP"></p>   
</body>  
</html>
復制代碼

 上述代碼(在網上粘貼而來)在新版ie瀏覽器運行起來,會報錯“SCRIPT438: 對象不支持“load”屬性或方法”;但是你如果用ie仿真模式ie10以下瀏覽器是可以保存成功的。

2、cookie存儲方式;

特點:在會話結束時到期,也可以設置時間戳控制到期時長;如果要傳到后台讀取,key/value需要url編碼,通過請求頭儲存並http請求到后端(瀏覽器自發的);大小4kb,不同瀏覽器個數也有限制;(https://segmentfault.com/a/1190000004743454該篇博客很全)

實例(創建cookie,通過node服務接收)

html代碼:

復制代碼
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<script type="text/javascript">
    //cookieUtil.js
    var cookieUtil = {
        //讀取"name"對應cookie的值
        get : function(name){
                var cookieName = encodeURIComponent(name)+"=",                //對傳入name參數URL編碼
                    cookieStart = document.cookie.indexOf(cookieName),
                    cookieValue = null; 
                if(cookieStart > -1){
                    var cookieEnd = document.cookie.indexOf(";",cookieStart);
                    if(-1 == cookieEnd){
                        cookieEnd = document.cookie.length;            //cookie值為空
                    }
                    //對cookie保存的值URL解碼
                    cookieValue = decodeURIComponent(document.cookie.substring(cookieStart+cookieName.length,cookieEnd));
                }
           return cookieValue;
            },
            
        //創建或設置cookie其中name將作為某一域內的唯一標示、不可更改
        set : function(name,value,expires){
            //對名稱和值URL編碼
            var cookieText = encodeURIComponent(name)+"="+encodeURIComponent(value);
            
            if(expires instanceof Date){
                cookieText += "; expires="+expires.toGMTString();
            }
            //將根據name是否存在決定是否添加新的cookie字符串,需要注意:a、cookie長度(limit:4095B);b、每個域允許的cookie個數(各瀏覽器決定)
            document.cookie = cookieText;        
        },
        
        //刪除cookie
        unset : function(name,path,domain,secure){
            this.set(name,"",new Date(0),path,domain,secure);
        }
        
    }
    cookieUtil.set("username",user,30);
</script>
<body></body>

</html>
復制代碼

node服務代碼:

復制代碼
var http = require('http');
var express = require("express");
var app = express();
app.use(express.static("web"));
http.createServer(function (req, res) {
    // 獲得客戶端的Cookie
    var Cookies = {};
    req.headers.cookie && req.headers.cookie.split(';').forEach(function( Cookie ) {
        var parts = Cookie.split('=');
        Cookies[ parts[ 0 ].trim() ] = ( parts[ 1 ] || '' ).trim();
    });
    console.log(Cookies)
    // 向客戶端設置一個Cookie
    res.writeHead(200, {
        'Set-Cookie': 'myCookie=test',
        'Content-Type': 'text/plain'
    });
    res.end('Hello World\n');
}).listen(8887);
復制代碼

3、localstorage存儲方式;

 特點:存儲的值是字符串格式,大小一般在5mb左右,能永久性存儲;

寫入語法:

window.localStorage["j"]=1;

window.localStorage.d=2;

window.localStorage.setItem("j",3);

讀取語法:

window.localStorage["j"];

window.localStorage.d;

window.localStorage.getItem("j");

修改語法跟寫入語法一樣,只是修改鍵值;

刪除語法:

window.localStorage.clear();

window.localStorage.removeItem("j");

4、sessionStorage儲存方式;

特點:

(臨時保存同一窗口或標簽頁)的數據,在關閉窗口或標簽頁之后將會刪除這些數據。seesionStorage的存儲方式采用key、value的方式。value的值必須為字符串類型(傳入非字符串,也會在存儲時轉換為字符串。true值會轉換為"true")

語法:

sessionStorage.key(int index) :返回當前 sessionStorage 對象的第index序號的key名稱。若沒有返回null。

 sessionStorage.getItem(string key) :返回鍵名(key)對應的值(value)。若沒有返回null。

sessionStorage.setItem(string key, string value) :該方法接受一個鍵名(key)和值(value)作為參數,將鍵值對添加到存儲中;如果鍵名存在,則更新其對應的值。

sessionStorage.removeItem(string key) :將指定的鍵名(key)從 sessionStorage 對象中移除。

sessionStorage.clear() :清除 sessionStorage 對象所有的項。

5 Application cache的用法(應用緩存)

html5之前的網頁,都是無連接,必須聯網才能訪問,這其實也是web的特色,這其實對於PC是時代問題並不大,但到了移動互聯網時代,設備終端位置不再固定,依賴無線信號,網絡的可靠性變得降低,比如坐在火車上,過了一個隧道(15分鍾),便無法訪問網站,這對於web的傷害是很大的,比如對於 《ecmascript合集》這樣的為閱讀而生的頁面。
html5便引入了cache manifest 文件。那么什么是cache manifest呢,接下來會講到。

什么是應用程序緩存(Application Cache)?

HTML5 引入了應用程序緩存,這意味着 web 應用可進行緩存,並可在沒有因特網連接時進行訪問。
應用程序緩存為應用帶來三個優勢:

離線瀏覽 - 用戶可在應用離線時使用它們

速度 - 已緩存資源加載得更快

減少服務器負載 - 瀏覽器將只從服務器下載更新過或更改過的資源。

支持版本

主流瀏覽器皆支持,IE8 IE9除外。

離線存儲技術

HTML5提出了兩大離線存儲技術:localstorage與Application Cache,兩者各有應用場景;傳統還有離線存儲技術為Cookie。

經過實踐我們認為localstorage應該存儲一些非關鍵性ajax數據,做錦上添花的事情;

Application Cache用於存儲靜態資源,仍然是干錦上添花的事情;

而cookie只能保存一小段文本(4096字節);所以不能存儲大數據,這是cookie與上述緩存技術的差異之一,而因為HTTP是無狀態的,服務器為了區分請求是否來源於同一個服務器,需要一個標識字符串,而這個任務就是cookie完成的,這一段文本每次都會在服務器與瀏覽器之間傳遞,以驗證用戶的權限。

所以Application Cache的應用場景不一樣,所以使用也不一致。

Application Cache簡介

Application Cache的使用要做兩方面的工作:

① 服務器端需要維護一個manifest清單

② 瀏覽器上只需要一個簡單的設置即可

1

<html  manifest="demo.appcache">

以例子做說明:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

CACHE MANIFEST

CACHE:

# 需要緩存的列表

style1.css

1.jpg

01.js

http://localhost/applicationcache/02.js

http://localhost/applicationcache/zepto.js

NETWORK:

# 不需要緩存的

4.jpg

FALLBACK:

# 訪問緩存失敗后,備用訪問的資源,第一個是訪問源,第二個是替換文件*.html /offline.html

2.jpg/3.jpg

首先我這里報了一個錯:

1

Application Cache Error event: Manifest fetch failed (404)

這個錯誤的原因是:manifest 文件需要配置正確的 MIME-type,即 "text/cache-manifest"。必須在 web 服務器上進行配置,不同的服務器不一樣

1

2

3

4

5

6

7

8

9

10

11

12

13

\APPLICATIONCACHE

    01.js

    02.js

    1.jpg

    2.jpg

    3.jpg

    4.jpg

    demo.appcache

    index.html

    style1.css

    style2.css

    web.config

    zepto.js

這樣一來便可以離線應用了,這個時候就算斷網了,那些文件依舊能訪問

這里有一點值得注意,比如這里不帶/index.html他會將“applicationcache/”緩存,其實這個就是index.html

manifest 文件可分為三個部分:

CACHE MANIFEST - 在此標題下列出的文件將在首次下載后進行緩存

NETWORK - 在此標題下列出的文件需要與服務器的連接,且不會被緩存

FALLBACK - 在此標題下列出的文件規定當頁面無法訪問時的回退頁面(比如 404 頁面)

如圖所示,HTML5定義了幾個事件點,但是我們一般不會主動使用js去操作什么,大多數情況下,我們完全依賴瀏覽器的處理即可。

尺寸限制

Application Cache的尺寸限制統一在5M,我這里做一個測試:

如所示,兩個css文件依舊超過了5M這個時候

 

1

2

3

4

5

6

Document was loaded from Application Cache with manifest http://localhost/applicationcache/demo.appcache

index.html:1 Application Cache Checking event

index.html:6 GET http://localhost/applicationcache/style2.css net::ERR_FAILED

index.html:1 Application Cache NoUpdate event

index.html:11 GET http://localhost/applicationcache/2.jpg net::ERR_FAILED

index.html:12 GET http://localhost/applicationcache/3.jpg net::ERR_FAILED

如所示,style2已經不能緩存了,這個會造成什么問題呢?

比如我A頻道維護了自己的Application Cache,B頻道也維護了自己的,這個時候A頻道如果使用達到了一個峰值,會導致B頻道所有的緩存失效,所以:

建議Application Cache,存儲公共資源,不要存儲業務資源

一些問題

由更新機制來說,首次更新manifest時,因為頁面加載已經開始甚至已經完成,緩存更新尚未完成,瀏覽器仍然會使用過期的資源;瀏覽器是當Application Cache有更新時,該次不會使用新資源,第二次才會使用。這個時候update事件中執行window.reload事件。

1

2

3

window.applicationCache.addEventListener("updateready", function(){

    window.location.reload()

});

由上例可以知道,緩存的不只是顯示定義的文件,比如上例中的applicationcache/時便會默認保存index.html為映射的數據,並且包含demo.appcache文件,很多時候會遇到一次文件更新線上老是不更新,這個時候隨便在manifest配置文件中做一點修改即可更新。

比如我們將這里代碼做一個改變:

1

2

3

<html  manifest="demo.appcache">

=>

<html  manifest="demo1.appcache">

這個時候如果不做demo.appcache的更新的話,緩存將不會更新,原因是index.html被緩存了,檢測的仍然是原manifest清單

各個頁面統一管理自己的manifest清單,意思是a頁面配置了common.js,b頁面也配置了common.js,意思是a頁面更新后,b頁面的manifest不更改的話,b頁面依舊讀取的是老版本的文件,這個有一定道理卻也有一定浪費,需要公共頁面做處理。

總結

從可用性與易用性來說,Application Cache是值得使用的,但是最好是做靜態資源的緩存,真正要實現離線應用還得花更多的功夫呢!


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM