【问题标题】:How to cache XMLHttpRequest response in Javascript?如何在 Javascript 中缓存 XMLHttpRequest 响应?
【发布时间】:2017-01-08 19:13:56
【问题描述】:

我有一个异步加载我的 html 模板的函数:

loadTplAsync: function(path) {

        return Q.Promise(function(resolve, reject) {
            var xhr = new XMLHttpRequest();
            xhr.open("GET", path, true);
            xhr.onload = () => {
                if (xhr.readyState === 4) {
                    if (xhr.status === 200) {
                        resolve(_.template(xhr.responseText));
                    } else {
                        reject(xhr.responseText);
                    }
                }
            };

            xhr.onerror = error => reject(error);
            xhr.send(null);
        });
    }

如何扩展此功能以缓存浏览器响应?

【问题讨论】:

标签: javascript ajax templates caching


【解决方案1】:

假设缓存的意思不是在页面加载的生命周期内重复发出相同的请求,您可以将承诺存储为变量并每次返回相同的承诺。

第一次请求特定路径时会发出新的请求,以后只会返回存储的promise

var promises ={};
loadTplAsync: function(path) {
        // create new promise if it doesn't already exist for path instance
        if(!promises[path]){
          promises[path] = Q.Promise(function(resolve, reject) {
            var xhr = new XMLHttpRequest();
            xhr.open("GET", path, true);
            xhr.onload = () => {
                if (xhr.readyState === 4) {
                    if (xhr.status === 200) {
                        resolve(_.template(xhr.responseText));
                    } else {
                        reject(xhr.responseText);
                    }
                }
            };

            xhr.onerror = error => reject(error);
            xhr.send(null);
        });
      }
      // return the stored promise
      return promises[path];
    }

请注意,这不是永久缓存,并且会在后续页面加载时发出新请求

【讨论】:

    猜你喜欢
    • 2014-07-05
    • 2013-08-30
    • 2023-04-05
    • 2016-11-29
    • 2016-11-14
    • 2012-01-17
    • 1970-01-01
    • 2011-06-24
    • 2015-03-25
    相关资源
    最近更新 更多