Web Storage的API曾经是Cookie API一个显著的进步,并且为开发者使用了很多年了。这个API是合理的,更大存储量的,而且是更为健全理智的。一种策略是去使用Session存储来存储非必要的,更为静态的内容,例如侧边栏的HTML内容,从Ajax加载进来的文章内容,或者一些其他的各种各样的片断,是我们只想请求一次的。
我们可以使用JavaScript编写一段代码,利用Web Storage使这些内容加载更加简单:
define ( function () { var cacheObj = window . sessionStorage || { getItem : function ( key ) { return this [ key ]; }, setItem : function ( key , value ) { this [ key ] = value ; } }; return { get : function ( key ) { return this . isFresh ( key ); }, set : function ( key , value , minutes ) { var expDate = new Date (); expDate . setMinutes ( expDate . getMinutes () + ( minutes || 0 )); try { cacheObj . setItem ( key , JSON . stringify ({ value : value , expires : expDate . getTime () })); } catch ( e ) { } }, isFresh : function ( key ) { // 返回值或者返回false var item ; try { item = JSON . parse ( cacheObj . getItem ( key )); } catch ( e ) {} if (! item ) return false ; // 日期算法 return new Date (). getTime () > item . expires ? false : item . value ; } } });
这个工具提供了一个基础的get和set方法,同isFresh方法一样,保证了存储的数据不会过期。调用方法也非常简单:
require ([ 'storage' ], function ( storage ) { var content = storage . get ( 'sidebarContent' ); if (! content ) { // Do an AJAX request to get the sidebar content // ... and then store returned content for an hour storage . set ( 'sidebarContent' , content , 60 ); } });
现在同样的内容不会被重复请求,你的应用运行的更加有效。花一点儿时间,看看你的网站设计,将那些不会变化,但是会被不断请求的内容挑出来,你可以使用Web Storage工具来提升你网站的性能。