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是值得使用的,但是最好是做静态资源的缓存,真正要实现离线应用还得花更多的功夫呢!

猜你喜欢

转载自www.cnblogs.com/fs0196/p/12684365.html