我有一个异步加载我的 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);
});
}
如何扩展这个功能来缓存浏览器的响应?
最佳答案
假设缓存的意思不是在该页面加载的生命周期内重复发出相同的请求,您可以将 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];
}
请注意,这不是持久缓存,新请求将在后续页面加载时发出
关于javascript - 如何在 Javascript 中缓存 XMLHttpRequest 响应?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41536714/