不同浏览器上的缓存实现
在浏览器的缓存数据的方式除了cookie之外,还可以有其他方法,但各个浏览器的支持的方法不一样,比如ie就不支持localstorage,写了一个util来屏蔽浏览器中实现缓存的差异,但是有些差异是不可避免的,比如存储的大小。
/** * 根据浏览器的类型,判断出存储数据的方式 * @enum {number} *<pre> *[saveType = 1] 利用localStorage 的方式存储数据 *[saveType = 0] 利用userdata 方式存储数据 ie 浏览器 *</pre> */ var saveType = 2, uniqueinstance, object,_OTos = Object.prototype.toString, _oArray = "[object Array]", _oObject = "[object Object]"; /** * ie 中保存数据 * @param args {object} * <pre> * { * file : '', IE6浏览器的域对象 一个对象中只能使用一次第二次使用将覆盖原始值,其他浏览器中该值无效 * key : '', 键的名称 * content : object 值的内容 类型可以是number object array string * } *</pre> */ function _saveIEData(args){ var content = args.content, key = args.key, vtype; vtype = _OTos.apply(content); if (vtype == _oArray || vtype == _oObject){ content = JSON.encode(content); } object.setAttribute(key, content); object.save(args.file); } function _loadIEData(args){ /** * 读取数据的类型 * {string|object|array} */ var type = args.type, file = args.file, content; object.load(file); content = object.getAttribute(args.key); if (type == "array" || type == "object"){ content = JSON.decode(content); } return content; } function _deleteIEData(args){ var file = args.file; object.load(file); object.expires = new Date(315532799000).toUTCString(); object.save(file); } /** * 利用localstorage 存储 读取 数据 */ function _saveCommonData(args){ var content = args.content, k = args.key, vtype ; vtype = _OTos.apply(content); if (vtype == _oObject || vtype == _oArray){ content = JSON.encode(content); } localStorage[k] = content; } function _deleteCommonData(args){ localStorage.removeItem(args.key); } function _loadCommonData(args){ var type = args.type , key = args.key, avalues = localStorage.getItem(key); if (type == "array" || type == "object"){ avalues = JSON.decode(avalues); } return avalues; } /** * 真实的localstorage对象 * 初始化时判断使用localstorage的方式根据浏览器的版本选择 * 当没有浏览器支持该对象时返回一个null 对象 */ function constructor(){ if (typeof localStorage != "undefined"){ saveType = 1; } else if(typeof MT.DOC.documentElement.style.behavior != undefined){ saveType = 0; if(typeof object == "undefined"){ object = MT.DOC.documentElement; object.style.behavior = "url('#default#userdata')"; } } else{ return null; } this.constructor = LocalStorage; this.saveData = function(args){ this.saveData = saveType ? _saveCommonData : _saveIEData; this.saveData(args); }; this.loadData = function(args){ this.loadData = saveType ? _loadCommonData : _loadIEData; return this.loadData(args); } this.deleteData = function(args){ this.deleteData = saveType ? _deleteCommonData : _deleteIEData; this.deleteData(args); } } var LocalStorage = { /* * @memberof LocalStorage * 惰性实例化 单例 */ getInstance: function(){ if(!uniqueinstance){ uniqueinstance = new constructor(); } return uniqueinstance; } }