本次项目需要用到前台缓存,使用了LocalStorage、sessionStorage
,但使用过程中报异常,原因及解决方法如下:

缓存到LocalStorage

调用localStorage.setItem方法保存缓存对象。一般来说,只要这一行代码就能完成本步骤。但是LocalStorage保存的数据是有大小限制的!我利用 chrome 做了一个小测试,保存500KB左右的东西就会令 Resources 面板变卡,2M 几乎可以令到 Resources 基本卡死,到了 5M 就会超出限制,sessionStorage也是一样的,浏览器抛出异常:


DOMException: Failed to execute 'setItem' on 'Storage': Setting the value of 'xxxxx' exceeded the quota.
    at Error (native)

因此需要使用 try catch 对localStorage.setItem方法进行异常捕获。当没容量不足时就需要根据保存时间逐一删除 LocalStorage 的缓存对象。

                   /**
                     * 把缓存对象保存到localStorage中
                     * @param {string} key ls的key值
                     * @param {object} storeObj ls的value值,缓存对象,记录着对应script的对象、有url、execute、key、data等属性
                     * @returns {boolean} 成功返回true
                     */
                    var addLocalStorage =function( key, storeObj ){
// localStorage对大小是有限制的,所以要进行try catch
// 500KB左右的东西保存起来就会令到Resources变卡
// 2M左右就可以令到Resources卡死,操作不了
// 5M就到了Chrome的极限
// 超过之后会抛出如下异常:
// DOMException: Failed to execute 'setItem' on 'Storage': Setting the value of 'basket-http://file.com/ykq/wap/v3Templates/timeout/timeout/large.js' exceeded the quota
                        try{
                            localStorage.setItem( storagePrefix + key, JSON.stringify( storeObj ));
                            return true;
                        }catch( e ){
// localstorage容量不够,根据保存的时间删除已缓存到ls里的js代码
                            if( e.name.toUpperCase().indexOf('QUOTA')>=0){
                                var item;
                                var tempScripts =[];
// 先把所有的缓存对象来出来,放到 tempScripts里
                                for( item in localStorage ){
                                    if( item.indexOf( storagePrefix )===0){
                                        tempScripts.push( JSON.parse( localStorage[ item ]));
                                    }
                                }
// 如果有缓存对象
                                if( tempScripts.length ){
// 按缓存时间升序排列数组
                                    tempScripts.sort(function( a, b ){
                                        return a.stamp - b.stamp;
                                    });
// 删除缓存时间最早的js
                                    basket.remove( tempScripts[0].key );
// 删除后在再添加,利用递归完成
                                    return addLocalStorage( key, storeObj );
                                }else{
// no files to remove. Larger than available quota
// 已经没有可以删除的缓存对象了,证明这个将要缓存的目标太大了。返回undefined。
                                    return;
                                }
                            }else{
// some other error
// 其他的错误,例如JSON的解析错误
                                return;
                            }
                        }
                    };
使用sessionStorage和会和上述情况一样,按此解决就行
Logo

Agent 垂直技术社区,欢迎活跃、内容共建。

更多推荐