Can you provide some insight on how to store XMLHttpRequest response in Javascript for future

I have a function in my codebase that is responsible for loading HTML templates asynchronously:

loadTemplate: function(url) {
        return new Promise(function(resolve, reject) {
            var xhr = new XMLHttpRequest();
            xhr.open("GET", url, true);
            xhr.onload = function() {
                if (xhr.readyState === 4) {
                    if (xhr.status === 200) {
                        resolve(_.template(xhr.responseText));
                    } else {
                        reject(xhr.responseText);
                    }
                }
            };
            xhr.onerror = function(error) {
                reject(error);
            };
            xhr.send(null);
        });
    }
    

I am now seeking advice on how to enhance this function by implementing response caching within the user's browser. Any suggestions or tips would be greatly appreciated!

Answer №1

If by "cache" you are referring to avoiding redundant requests during the lifespan of a page load, one approach is to store the promise in a variable and return it whenever needed.

When a specific path is first requested, a new request is made. Subsequent requests for the same path will simply return the stored promise.

var promises ={};
loadTplAsync: function(path) {
        // create a new promise only if it doesn't already exist for the given path
        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];
    }

It's important to note that this method does not constitute a persistent cache; new requests will be made upon subsequent page reloads.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Grab the code snippet from JSFiddle

I apologize for the seemingly simple question, but I have been struggling with it. I tried looking at similar questions, but I couldn't find a solution. Despite copying the code from http://jsfiddle.net/sB49B/21/, I can't seem to get it to work ...

What is the reasoning behind placing CDN links at the bottom of the index file?

What is the reason for placing CDN links for AngularJS file at the end of the index page? I initially placed it at the top of the file and it worked fine. Is there a significant difference between these two placements? ...

In order to locate a matching element within an array in a JSON file and update it, you can use Node

Good day, I have a script that updates the value in a JSON file const fsp = require('fs').promises; async function modifyNumberInFile() { try { let data = await fsp.readFile('example.json'); let obj = JSON.parse(dat ...

Utilizing JQuery to extract data from a <select> dropdown menu

Is there a way to retrieve the current value of a SELECT tag using JavaScript or jQuery? I have tried using $('select').val(), but it only returns the default value and does not update when changed. Any suggestions on how to solve this issue? $( ...

Encountering Issues with Ajax Request in the Google Play App

I am facing an issue with my Phonegap app. It functions perfectly in debug mode and when installed as an apk file from Phonegap. However, when I upload it to Google Play Store and then download it from there, my ajax requests stop working. I have added the ...

Synchronous execution of functions in Node.js

I need to ensure that func2 is only called after func1 has completed its execution. { func1(); func2();// } However, the issue arises when func1() starts running and func2() does not wait for it to finish. This leads to a runtime error as func2() require ...

Issue encountered while trying to load electron-tabs module and unable to generate tabs within electron framework

I've recently set up the electron-modules package in order to incorporate tabs within my Electron project. Below are snippets from the package.json, main.js, and index.html files. package.json { "name": "Backoffice", "version": "1.0.0", "descr ...

Is there a way to retrieve the value from a select tag and pass it as a parameter to a JavaScript function?

I would like to pass parameters to a JavaScript function. The function will then display telephone numbers based on the provided parameters. <select> <option value="name-kate">Kate</option> <option value="name-john">John& ...

To avoid TS2556 error in TypeScript, make sure that a spread argument is either in a tuple type or is passed to a rest parameter, especially when using

So I'm working with this function: export default function getObjectFromTwoArrays(keyArr: Array<any>, valueArr: Array<any>) { // Beginning point: // [key1,key2,key3], // [value1,value2,value3] // // End point: { // key1: val ...

Incorporate the value of a JQuery variable within an HTML form

When the Submit button is clicked, I am attempting to pass the value of currentDate to a REST GET service. However, there are two things that I don't understand. Is it possible to include the URL of the REST service in the action attribute of the fo ...

Comparing and highlighting words in strings using JavaScript

Seeking assistance with comparing and styling words as shown in the image below: https://i.stack.imgur.com/Ffdml.png I attempted using JavaScript for this task but have not been successful so far. <div class="form-group"> <div class="col-md ...

What is the best method for transforming a stream into a file with AngularJS?

Currently, I have a server returning a file stream (StreamingOutput). My goal is to convert this file stream into an actual file using AngularJS, javascript, JQuery, or any other relevant libraries. I am looking to display the file in a <div> or ano ...

When running npm install, the dist folder is not automatically generated

I found a helpful tutorial at this link for creating a Grafana plugin. However, when I tried copying the code from this link to my test server (without the dist/ folder) and ran npm install, it did not generate a new dist/ folder but created a node_module ...

Ensuring model accuracy in Asp.Net Core prior to initiating an Ajax request via JavaScript

Here is a snippet of code that I am currently using, which is triggered on a button click event. The question I have is regarding the validation of my viewmodel object before sending an ajax call. I can see model errors in JavaScript, but I'm unsure o ...

Is it better to include the Google Analytics code in the master page or on every individual page of an asp.net

Looking for a way to track every page on my website effectively. Should I insert the Analytics tracking code in each aspx page inherited from the master page, or is it sufficient to place it only in the master page to track all inherited pages? ...

Experiencing problems with npm and bower installations, along with deprecated modules while setting up angular-phonecat project

Trying to execute npm install in terminal while setting up angular-phonecat based on instructions from https://docs.angularjs.org/tutorial Encountering issues with deprecated modules and errors during the bower install phase. Seeking advice on how to upd ...

Enhancing data management with Vuex and Firebase database integration

Within my app, I am utilizing Firebase alongside Vuex. One particular action in Vuex looks like this: async deleteTodo({ commit }, id) { await fbs.database().ref(`/todolist/${store.state.auth.userId}/${id}`) .remove() .then ...

Updates to Firebase data do not automatically reflect in Google Charts

I've successfully connected my Firebase to Google Charts, however I am facing an issue in displaying a 'no data' message when there is no data available. Currently, I have set a Firebase data value of 'NA' for a single user, which ...

Expiration Date of Third-Party Cookies

I need help retrieving the expiration date of a third-party cookie programmatically using JavaScript. Even though I can see the expiry time in the browser's DevTools (refer to the screenshot at ), I am struggling to figure out how to access this infor ...

Trouble with Add To Cart feature in React app due to issues with Context API

I have been following a tutorial located here. I followed the steps exactly and even checked the code on the related github repository, which matches. However, when I try to add a product to the cart by clicking the button, the state does not update. In Re ...