Reputation: 55
I have a function that loads my html templates asynchronously:
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);
});
}
How to extend this function to cache responses by browser?
Upvotes: 4
Views: 1455
Reputation: 171700
Assuming that what you mean by cache is not to repeat making same request during life cycle of that page load you could store the promise as a variable and return the same promise each time.
The first time a specific path is requested will make a new request, subsequent times only the stored promise will be returned
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];
}
Note this is not a persistent cache and new requests would be made on subsequent page loads
Upvotes: 3