Z
Z
ZaxapKramer2016-07-02 07:16:35
JavaScript
ZaxapKramer, 2016-07-02 07:16:35

XMLHttpRequest; How to cache query results before page reload?

Hello. I'm making a small site using Ajax - XMLHttpRequest.
I found JQuery too heavy for these things (the largest page weighs about 100kb, JQuery - 85kb), I use native js.
HTML5 History API, when changing the address in the browser line, the content from the corresponding php files is loaded (for example, when going to /page/1 , /index.php?page=1 is given ).

It is necessary that when you go to the previous / next pages (the "Back" / "Forward" buttons in the browser), already cached results are returned, so as not to load everything anew each time. How can this be done without jQuery?(not for a year or two, but just until the page is reloaded)? Or is this kind of caching included in XMLHttpRequest by default (which I did not see, perhaps due to a lack of understanding of how this can be checked at all, and ignorance)?
PS Google gives a lot of information on how to disable caching in XMLHttpRequest or enable it in JQuery, but there is practically no word on enabling this in XMLHttpRequest.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
E
Eugene, 2016-07-02
@ZaxapKramer

Well, you can do something like this, start a cache, check if the current page is in it, if yes, then give it away, if not, send a request, put it in the cache:

'use strict';

let cache = {};
let url = '/index.php?page=1';

const page = document.querySelector('.page');

if (!cache[url]) {
    fetch(url)
        .then((response) => {
            return response.text();
        })
        .then((data) => {
            cache[url] = data;
            page.innerHTML = data;
        });
} else {
    page.innerHTML = cache[url];
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question