如何在Javascript中缓存XMLHttpRequest响应?

3

我有一个函数可以异步加载我的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);
        });
    }

如何将此功能扩展为通过浏览器缓存响应?

请查看此链接 https://dev59.com/i4fca4cB1Zd3GeqPgUKg - Aman Rawat
你尝试过使用 ServiceWorkerCache API吗? - guest271314
https://www.mnot.net/cache_docs/ - Quentin
1个回答

3
假设您所说的缓存是指在页面加载期间不重复发出相同请求,那么您可以将 Promise 存储为变量,并每次返回相同的 Promise。
第一次请求特定路径时会发起新请求,随后的请求只会返回已存储的 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];
    }

请注意,这不是持久缓存,后续页面加载时将进行新的请求。

如何进行持久性缓存? - K Pradeep Kumar Reddy

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接