luohongxia

有时需要将网页中的一些数据保存在浏览器端,这样做的好处是,当下次访问页面时,不需要再次向服务器请求数据,直接就可以从本地读取数据。目前常用的有以下几种方法:

cookie

cookie会随着每次HTTP请求头信息一起发送,无形中增加了网络流量,另外,cookie能存储的数据容量有限,根据浏览器类型不同而不同,IE6大约只能存储2K。

Flash ShareObject

这种方式能能解决上面提到的cookie存储的两个弊端,而且能够跨浏览器,应该说是目前最好的本地存储方案。不过,需要在页面中插入一个Flash,当浏览器没有安装Flash控件时就不能用了。所幸的是,没有安装Flash的用户极少。

缺点:需要安装Flash插件。

Google Gear

Google开发出的一种本地存储技术。

缺点:需要安装Gear组件。

userData

IE浏览器可以使用userData来存储数据,容量可达到640K,这种方案是很可靠的,不需要安装额外的插件。缺点:它仅在IE下有效。

sessionStorage

使用于Firefox2+的火狐浏览器,用这种方式存储的数据仅窗口级别有效,同一个窗口(或者Tab)页面刷新或者跳转,都能获取到本地存储的数据,当新开窗口或者页面时,原来的数据就失效了。

缺点:IE不支持、不能实现数据的持久保存。

globalStorage

使用于Firefox2+的火狐浏览器,类似于IE的userData。

JAVASCRIPT:

复制代码
//赋值
globalStorage[location.hostname][\'name\'] = \'tugai\';
//读取
globalStorage[location.hostname][\'name\'];
//删除
globalStorage[location.hostname].removeItem(\'name\');
复制代码

缺点:IE不支持。

localStorage

localStorage是Web Storage互联网存储规范中的一部分,现在在Firefox 3.5、Safari 4和IE8中得到支持。

缺点:低版本浏览器不支持。

结论:
Flash shareobject是不错的选择,如果你不想在页面上嵌入Flash,可以结合使用userData(IE6+)和globalStorage(Firefox2+)和localStorage(chrome3+)实现跨浏览器。

补充:由于项目需要,简单模拟了HTML5 localStorage中的几个方法,支持firefox2+,IE5+,chrome3+,其他不详。

JAVASCRIPT:

复制代码
if (!(\'localStorage\' in window)) {
 
   window.localStorage = (function() {
       var documentElement, isIE = !!document.all;
 
       if (isIE) {
           documentElement = document.documentElement;
           documentElement.addBehavior(\'#default#userdata\');
       }
 
       return {
           setItem: function(key, value) {
               if (isIE) {
                   documentElement.setAttribute(\'value\', value);
                   documentElement.save(key);
               }
               else {
                   window.globalStorage[location.hostname][key] = value;
               }
           },
           getItem: function(key) {
               if (isIE) {
                   documentElement.load(key);
                   return documentElement.getAttribute(\'value\');
               }
 
               return window.globalStorage[location.hostname][key];
           },
           removeItem: function(key) {
               if (isIE) {
                   documentElement.removeAttribute(\'value\');
                   documentElement.save(key);
               }
               else {
                   window.globalStorage[location.hostname].removeItem(key);
               }
           }
       };
   })();
 
}
 
//写入
localStorage.setItem(\'name\', \'shuiniuer\');
//读取
localStorage.getItem(\'name\');
//删除
localStorage.removeItem(\'name\');

分类:

技术点:

相关文章: