javascripthtml

Is it possible to know if a linked resource with preload rel attribute is already loaded?


I can attach an event listener for the load event, but if the link is already loaded it will never trigger. Is there any way to check if it already loaded?

For images there is an .complete attribute that will make the trick and for <link rel="stylesheet"> there is .sheet, but I could find nothing for the preload link.

Why?

There is a modern (but verbose) way to add asynchronous stylesheets using:

<link rel="preload" href="async.css" as="style" onload="this.rel='stylesheet'">

It does work, but looks ugly because of the inline event handler, but I could not find any alternative because the "load" event does not bubble and there is no way to know if the resource is already loaded or not.


Solution

  • You can check if the request is part of the exposed resource timing entries. If not, then it's probably still running.

    const test = () => {
      const link = document.querySelector("link");
      const entry = performance.getEntriesByType("resource").find(({ name }) => name === link.href);
      if (!entry) {
        console.log("not yet loaded"); // attach a load event listener here
      }
      else {
        console.log("already loaded"); // run the callback directly
      }
    }
    
    document.querySelector("button").onclick = test;
    test();
    <!-- Using a delaying API so that the request ends in about 2s -->
    <link rel="preload"
      href="https://app.requestly.io/delay/2000/https://cdn.sstatic.net/Shared/Channels/channels.css"
      as="style"
      onload="console.log('load event fired')">
    <button>Run test again</button>