4

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?

3

1 Answer 1

3

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

Sign up to request clarification or add additional context in comments.

1 Comment

How to do the persistent cache ?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.