<link rel="preload" href="main.js" as="script">
Link rel=preload is useful for downloading any important resource more quickly, such as stylesheets that contain critical CSS, fonts that are used in important design elements, and hero images. It's especially important for scripts because they block page content from rendering and consume the most CPU during page load. (We'll explore this topic in the next post in this series.)
as attribute is critical. The browser uses this value when determining the download priority. Possible values included script, style, font, image, video, audio, and more. Only use preload for truly critical content, otherwise less important content will consume bandwidth and CPU that would have been better allocated to what matters most. In the case of scripts, link rel=preload is best for the first few synchronous scripts in the page.
Link rel=preload has been around for awhile, but is lesser known in the dev community. Nevertheless, Chrome reports that 25% of web pages visited using Chrome have this feature.
While true, this might overstate the adoption of link rel=preload where it matters most. Instead of including all uses of link rel=preload, I did an analysis based on HTTP Archive data to see how many sites use link rel=preload to download scripts for their page. That number turned out to be closer to 1% (12,469 pages out of 1,255,904). This visualization helps make my point:
The browser has a built-in Preloader which helps get scripts downloading sooner. Using link rel=preload in the markup might accelerate that even more, depending on the structure of your HTML document. It's likely to have a bigger impact, however, if you serve it as an HTTP response header, like this:
Link: <main.js>; rel="preload"; as="script"
This HTTP response header is received by the browser before the HTML, so could initiate the script request even sooner. It's best to do both the HTTP response header and the markup as some browsers don't yet support link rel=preload response headers.
We know that synchronous scripts block rendering, which makes the user experience feel slow. And we know that most scripts today are downloaded synchronously (rather than async). And yet only 1% of sites are using link rel=preload to download their scripts. If your site has any synchronous scripts, do an A/B test adding link rel=preload for them. It's likely this will be a win and help you create a more joyous experience for your users.