1

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);
Zanon
  • 29,231
  • 20
  • 113
  • 126

2 Answers2

2

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);
Zanon
  • 29,231
  • 20
  • 113
  • 126
1

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

ChaseMoskal
  • 7,151
  • 5
  • 37
  • 50
  • 1
    Sorry, but I'm sure that I want to prefetch (download something that might be necessary in the future with low priority) instead of preload (force the browser to download something with high priority). – Zanon Sep 08 '19 at 22:25
  • mdn mentions that preload is higher priority than prefetch, but that makes sense to me — i don't think the priority is any higher than you'd want — however, alternatively, you can just write a `fetch()` call to execute whenever you want, store that result, and then make use of it later on — this is something you can manage manually, and choose to start loading whenever you want (perhaps after page load) – ChaseMoskal Sep 08 '19 at 22:45
  • Thanks, but prefetching manually is something that I've done in the past in another project. I would prefer now to use the modern `` to do it automatically. – Zanon Sep 08 '19 at 23:13