前端性能优化:网络存储的静态缓存和非必要内容优化 Web Storage

来源:互联网 发布:为什么会有网络诈骗 编辑:程序博客网 时间:2024/05/01 15:46

Web Storage的API曾经是Cookie API一个显著的进步,并且为开发者使用了很多年了。这个API是合理的,更大存储量的,而且是更为健全理智的。一种策略是去使用Session存储来存储非必要的,更为静态的内容,例如侧边栏的HTML内容,从Ajax加载进来的文章内容,或者一些其他的各种各样的片断,是我们只想请求一次的。

我们可以使用JavaScript编写一段代码,利用Web Storage使这些内容加载更加简单:

  1. define(function() {
  2.  
  3. var cacheObj = window.sessionStorage || {
  4. getItem: function(key) {
  5. return this[key];
  6. },
  7. setItem: function(key, value) {
  8. this[key] = value;
  9. }
  10. };
  11.  
  12. return {
  13. get: function(key) {
  14. return this.isFresh(key);
  15. },
  16. set: function(key, value, minutes) {
  17. var expDate = new Date();
  18. expDate.setMinutes(expDate.getMinutes() + (minutes || 0));
  19.  
  20. try {
  21. cacheObj.setItem(key, JSON.stringify({
  22. value: value,
  23. expires: expDate.getTime()
  24. }));
  25. }
  26. catch(e) { }
  27. },
  28. isFresh: function(key) {
  29. // 返回值或者返回false
  30. var item;
  31. try {
  32. item = JSON.parse(cacheObj.getItem(key));
  33. }
  34. catch(e) {}
  35. if(!item) return false;
  36.  
  37. // 日期算法
  38. return new Date().getTime() > item.expires ? false : item.value;
  39. }
  40. }
  41. });

这个工具提供了一个基础的get和set方法,同isFresh方法一样,保证了存储的数据不会过期。调用方法也非常简单: 

  1. require(['storage'], function(storage) {
  2. var content = storage.get('sidebarContent');
  3. if(!content) {
  4. // Do an AJAX request to get the sidebar content
  5.  
  6. // ... and then store returned content for an hour
  7. storage.set('sidebarContent', content, 60);
  8. }
  9. });

现在同样的内容不会被重复请求,你的应用运行的更加有效。花一点儿时间,看看你的网站设计,将那些不会变化,但是会被不断请求的内容挑出来,你可以使用Web Storage工具来提升你网站的性能。

原创粉丝点击