2

I would like to force the browser to preload a JavaScript worker as well as a WebAssembly script. When loaded, I have a ServiceWorker that puts these scripts in the CacheStorage.

For the images, I use the following <link> tag and this works well:

<link rel="prefetch" href="/img/foo.png" as="image" type="image/png" importance="low" />

So I tried the same things for my wasm and js scripts:

<link rel="prefetch" href="/wasm/bar.wasm" type="application/wasm" importance="low" />
<link rel="prefetch" href="/js/baz.worker.js" as="script" type="text/javascript" importance="low" />

However, it looks like the Browser (Chrome) does not load these scripts with the prefetch rel. So I tried to use rel="preload".

But I don't know what to fill for the as property for the wasm file and for the js worker file, I get the following warning: The resource http://localhost:3000/wasm/bar.wasm was preloaded using link preload but not used within a few seconds from the window's load event. Please make sure it has an appropriate `as` value and it is preloaded intentionally..

If the user executes an action that requires these files, the browser loads them well and then we can use them when offline.

These scripts are not needed before the load event. I could send a fetch request when the browser emits the load event? But I think it is better to let the browser manages such things with a link tag? In my case, it is quite likely that the user will need this script (90%+), so a preload would make sense, but theoretically, I want to make a prefetch of the content only.

How would you recommend preloading these files for offline use (pwa)?

Alexis Delrieu
  • 1,313
  • 2
  • 10
  • 19
  • 1
    "But I don't know what to fill for the as property for the wasm file and for the js worker file" - for JS you've correctly set "script", and for Wasm it should be "fetch" since the module is fetched as any other binary resource before compiling. – RReverser Oct 06 '21 at 17:55

1 Answers1

0

It looks like sending an HTTP request with the fetch API puts well the script into the CacheStorage.

/**
 * Preload resources for offline pwa use
 */
window.addEventListener('load', () => {
  fetch('/js/baz.worker.js');

  fetch('/wasm/bar.wasm');
});

By sending these requests after the load event, it does not disturb the page load time.

To keep the priority hint, it is possible to set the importance parameter to low like the following:

fetch('/wasm/bar.wasm', { importance: "low" });

(warning: limited browser support when this answer has been published)

Alexis Delrieu
  • 1,313
  • 2
  • 10
  • 19