web端存儲的幾種方式

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

userdata重點使用語法:php

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如下瀏覽器是能夠保存成功的。css

二、cookie存儲方式;html

特色:在會話結束時到期,也能夠設置時間戳控制到期時長;若是要傳到後臺讀取,key/value須要url編碼,經過請求頭儲存並http請求到後端(瀏覽器自發的);大小4kb,不一樣瀏覽器個數也有限制;(https://segmentfault.com/a/1190000004743454該篇博客很全)html5

實例(建立cookie,經過node服務接收)java

html代碼:node

複製代碼
<!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服務代碼:web

複製代碼
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);
複製代碼

三、localstorage存儲方式;ajax

 特色:存儲的值是字符串格式,大小通常在5mb左右,能永久性存儲;express

寫入語法:

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");

四、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是值得使用的,可是最好是作靜態資源的緩存,真正要實現離線應用還得花更多的功夫呢!

相關文章
相關標籤/搜索