简体   繁体   中英

How to prefetch an ajax call that returns a JSON format data in the browser

I have a use case wherein I am making multiple ajax calls when the page loads. The initial load fires off an ajax request to the server that gets the data in JSON format, upon subsequent user clicks other ajax calls are fired that make database calls to compute the JSON on the server side , the browser typically is idle and waits for the JSON to be returned. I was thinking of some ways in which I might be able to speed up the execution of this from the application side.

Is there a way in Jquery to fire off the subsequent ajax request before hand and save it somewhere on the client , so that when a user click happen the page the JSON gets parsed from the cache and rendered in the DOM instead of the delayed request to the server.

jQuery AJAX requests are being cached by the browser (assuming it is a GET request, POST will always hit the server). So if you can predict the calls most likely to happen, you can spin off a function during initialization to make these calls preemptively, and you should get the results for the subsequent calls from the browser cache. Make sure the server actually sends appropriate cache headers, though.

Another option would be to wrap the call to the jQuery AJAX function in a function of your own and hold the data in an array in memory. In this case, make sure you have a way of aging out old results at some point, or you will fill up the browsers memory.

What you can do is fire off all the AJAX requests when you load the page, and assign them to promise variables. When you need to use the result, use $.when()

var ajax1 = $.ajax( { ... } );
...
$.when(ajax1).then(function(response) {
    // Do what you need
});

You can

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM