Caching GET Response in Vanilla Javascript

I noticed that Firefox does not cache GET requests automatically. Following the code, I use:

var ajax = new XMLHttpRequest(); ajax.open("GET","page.php?val=" + val,true); ajax.send(); 

With jquery you can give cache: true; , how can I save in cache using Vanilla Javascript (client side)? You can also decide how long? Can you give me some sample code? Thank you in advance!

+4
source share
2 answers

Web caching is mainly controlled by headers sent from the server (Expires: etc.). Browsers sometimes β€œcheat” and do not actually cache, even if the headers allow them ... probably because the user used his user interface to disable caching, for example, setting the cache size to zero. But browsers that β€œtrick” another direction, in any case, cache, even if the headers do not allow this, are (for good reason) extremely unusual.

If caching is not performed for you, this is a file and server function (or, possibly, browser configuration), and not any type or version of the browser. (To say the same thing differently, your Firefox will cache just fine if the server sent the necessary headers.) Headers are managed in different ways by different servers and different providers. For the Apache server, nitty-gritty may be in a .htaccess file, whose pre-written templates are often available.

In a first approximation, with HTML4, you simply cannot control the caching of web pages from the client side, no matter what tool you use, and no matter what your program does. A general exception is provided by the new "online application cache" or "appcache" in HTML5 ... but with other restrictions, such as "one per site" and "the same origin."

+1
source

You can cache responses using a simple hash, for example:

 var cache = {}; function getData(variable) { if (cache[variable]) { return cache[variable]; } // previous ajax code to get the data... // in the response handler, do: cache[variable] = data; } 

This is a naive implementation of the caching mechanism: it only works for the lifetime of the page (i.e. until the page is refreshed or deleted), it does not have an expiration mechanism or other shortcomings, I am sure. For example, you can use localStorage to get around the update problem.

But hey, I’m not paid to write this :).

+1
source

Source: https://habr.com/ru/post/1493841/


All Articles