Can I use both preload and modulepreload to maximise browser compatibility?

152 Views Asked by At

I want to preload and early parse my javascript module code in my-module.js. For that I use link="modulepreload" which does exactly that. But modulepreload wasn't introduced in Safari until just 3 weeks ago and I want to make sure those with Safari pre version 17 still has the fastest possible experience. Can I just throw in a link="preload" as="script" before or will there be side effects?

In <head>:

<link rel="modulepreload" href="my-module.js" />

my-module.js:

export default function () {
    // ...
}

Use of my-module.js inline:

<script type="module">
    import mm from "my-module.js";
    mm();
</script>

For the sake of the question, let's assume I do need to execute the module script later, like before </body> and not just execute directly in <head>.

1

There are 1 best solutions below

0
Jonas Äppelgran On

The answer seems to be: No

I tested using both rel="preload" and rel="modulepreload". Different order did not make any difference.

Safari v17 has the behaviour I want - the resource is preloaded and only downloaded once.

Chrome v117 and Firefox v118 both downloads the resource twice. Not good. And they also double download if I only use rel="preload" for a module script (that I later import).

There is a Chromium bug on the double download when combining rel="preload" and module script. It says fixed, but it isn't (or it maybe it once was) and reading the discussion it seems like double download is according to spec.

I guess the solution is to only use rel="modulepreload" when using javascript modules. And to import important modules early.