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

Navigating the authorization header of an API request in a Node environment

const authHeader = req.headers["authorization"]; I have a question that may come across as basic - why do we use ["authorization"] instead of just .authorization? After some research, I discovered it had to do with case sensitivity but ...

Text that disappears upon clicking on show/hide按钮

Could someone please help me figure out how to prevent the "See more" text from disappearing when clicked in the example below? I want it to stay visible. Thank you! ...

Utilizing Various Styles within a single Google Sheets Cell

In Cell A1, I have a challenge where I need to merge 4 different arrays of names, separated by commas. Each name should have its own styling based on the array it belongs to - red for array1, green for array2, orange for array3, and gray with a strike-th ...

Transform a flat 2D shape into a dynamic 3D projection using d3.js, then customize the height based on the specific value from ANG

Currently, I am utilizing d3.js version 6 to generate a 3D representation of the 2D chart shown below. Within this circle are numerous squares, each colored based on its assigned value. The intensity of the color increases with higher values. My goal is t ...

Ways to retrieve my PHP output and display it on a page using Ajax

I'm struggling to combine the functionalities of a PHP script and Ajax on my website. I want to update content without reloading the page but facing issues. Although I can send input data through Ajax, I'm unable to retrieve the results effectiv ...

Is there a way I can utilize canvas to overlay one image onto another?

Is there a way to merge one image into another by using a transparent box? It's not just about copying and pasting an image into another. I also want to know how to transform the image to fit perfectly within the other image. For example, similar to ...

numerous sections within a solitary webpage

I need to implement multiple tabs on a single page, how do I modify the code to make this possible? Take a look at the codepen for reference. Here is the jquery code I have written so far: var tabs = $(".tabContainer ul li a"); $(".tabConten ...

Whenever a query is entered, each letter creates a new individual page. What measures can be taken to avoid this?

Currently, I am working on a project that involves creating a search engine. However, I have encountered an issue where each time a user types a query, a new page is generated for every alphabet entered. For instance, typing 'fos' generates 3 pag ...

Is there a way to begin using the :nth-child() selector from the last element instead of the first?

$('button').click(function(){ $('ul').find('li:nth-child(2)').css('color', '#f00') }) <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <ul> < ...

Enforce the instantiation of static members in a template

I am currently working on a program that runs certain code only when the template is utilized for low-level driver initialization purposes. Below is my current approach: class Initializer { public: Initializer(){ // This code will run once ...

Unraveling the Mystery of jQuery Syntax

Upon reviewing jquery.ui-1.8.11.js: $.extend(Datepicker.prototype, { /* A unique class name appended to elements indicating they are configured with a date picker. */ markerClassName: 'hasDatepicker', /* For debugging purposes (if e ...

Having trouble with GSAP CDN not functioning properly in your JavaScript or HTML document?

After watching a tutorial on YouTube by Gary Simon, I attempted to animate text using GSAP. Despite following the instructions meticulously and copying the CDN for GSAP and CSSRulePlugin just like him, nothing seems to be happening. Even setting my border ...

Please be patient for the PayPal script to load on the nextjs page

I've encountered an issue with my code that is meant to display PayPal buttons <Head> <script src="https://www.paypal.com/sdk/js?client-id=KEY"></script> </Head> The PayPal buttons are loaded within the ...

Identical HTML elements appearing across multiple DOM pages

My question might seem silly, but I'm facing an issue. I have several HTML pages such as index.html and rooms.html, along with a main.js file containing scripts for all of these pages. The problem arises because I have variables like const HTMLelemen ...

Using setInterval() does not automatically fetch JSON data at a specified interval for me

Attempting to constantly update the latitude and longitude coordinates from a dynamic API has proven to be a challenge. Despite utilizing jQuery with a set interval of 1000 milliseconds, the data retrieval from the API does not occur as expected. While i ...

React Modals: Only the modal component triggered by the first click will open, with no other modals opening

As a newcomer to StackOverflow, I apologize if my problem description is not clear. I am currently learning React and working on a course-search app as a project. The app filters courses based on user input from a JSON file and displays them in cards with ...

Determine in Node.js whether a variable is present in the request object for each page the user visits

Currently, my authentication system utilizes passportjs to define req.user when the user is logged in. As my website expands beyond its current 5 pages, I have been checking for the existence of req.user at the top of each route. Based on whether it exist ...

Press a single button to toggle between displaying and hiding the table

$(document).ready(function() { $("#t1").hide(); // hide table by default $('#sp1').on('click', function() { $("#t1").show(); }); $('#close').on('click', function() { $("#t1").hide(); }); }); <li ...

Interacting with a WebGL globe: accessing database information and displaying pop-up windows when clicking on specific locations on the globe

I am working on creating a WebGL Globe similar to the one found at this link: Currently, I have been using this example as a reference point: Here are the specific project requirements that I am aiming to achieve: The website needs to be able to manage ...

What code can I use to prompt clients to refresh JavaScript files automatically?

We are experiencing an issue where, even after pushing out updates with new JavaScript files, client browsers continue to use the cached version of the file and do not display the latest changes. While we can advise users to perform a ctrlF5 refresh during ...