Zanon
Zanon

Reputation: 30790

How to prefetch and use a JSON resource?

I want to prefetch a JSON resource and use it later in my JavaScript code when necessary.

I'm prefetching with:

<link rel="prefetch" href="/data.json" as="fetch">

But I don't know how to access this resource. As the data is loaded and cached, I thought that a fetch request would use the cache, but it is making a second request to the server (that I would like to avoid).

// a second request is sent to server instead of using the cache
fetch('/data.json').then(console.log);

Upvotes: 1

Views: 2762

Answers (2)

Zanon
Zanon

Reputation: 30790

I was using Chrome DevTools with the option Disable cache (while DevTools is open) enabled, so fetch was always sending a new request to the server without looking in the cache. After disabling this option, the resource is correctly retrieved from cache.

showing in devtools that the second request was loaded from cache

In the image above (DevTools network tab), the first line shows the request that was done to the server using the prefetch:

<link rel="prefetch" href="/data.json" as="fetch">

And the second line shows that I've done a fetch, but instead of going to the server again, the browser loaded the resource from the cache.

I've accessed the JSON file using the following:

// executed in a click event after the data.json was already prefetched
fetch('/data.json')
    .then(response => {
        if (!response.ok) {
            throw new Error("HTTP error " + response.status);
        }

        return response.json();
    })
    .then(json => {
        console.log(json); // do something
    })
    .catch(console.error);

Upvotes: 2

ChaseMoskal
ChaseMoskal

Reputation: 7681

you want to use "preload" instead of "prefetch", like so:

<link rel="preload" href="/data.json" as="fetch"/>

see the answer on this thread: Can link prefetch be used to cache a JSON API response for a later XHR request?

and also check out the mdn documents for preload: https://developer.mozilla.org/en-US/docs/Web/HTML/Preloading_content

Upvotes: 2

Related Questions