link prefetch not working properly, script is fetched again on navigation

1.7k views Asked by At

I am having a simple markup.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link rel="prefetch" href="page2.html">
    <link as="script" rel="prefetch" href="./src/script2.js">
</head>
<body>
    <p>Let's check</p>
    <a href="page2.html">Go to page 2 where script2 is there</a>
    <script src="./src/script1.js"></script>
</body>
</html>

Here I am prefetching the second script script2.js. It is prefetched successfully but when I click on page 2 link where I have my script tag script2.js, again script2 is downloaded it is not taking it from prefetch cache.

Here is the page2.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <p>This is page 2</p>
    <script src="./src/script2.js"></script>
</body>
</html>
3

There are 3 answers

2
Magnus Larsen On

Had similar issue and the cause for me was that I had disable cache enabled in Google Chrome.

You can see how to disable/enable caching in Chrome DevTools on this answer https://stackoverflow.com/a/7000899/2992661

0
Junior Tour On

If you are using some browser proxy plugin, eg: Switch-Omega, it will also disable prefetch cache.

After disable Switch-Omega Chrome plugin. The prefetch of my website finally works.

disable-switch-omega-plugin

0
zed On

I've been facing this issue for a while, just got a clue that HTTP header VARY will hurt prefetch cache. checkout the MDN description about VARY.

https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Vary

The Vary HyperText Transfer Protocol (HTTP) response header determines how to match future request headers. This information is required to decide whether or not a cached response can be served instead of requesting a fresh one from the origin server. This response header is used by the server to indicate the headers it used when selecting a representation of a resource in a content negotiation algorithm.

in my case, after i remove 'vary', the 'prefetch' script did load from 'prefetch cache'.