HTML has an attribute called preload
that allows you to give the browser a hint about how, and more importantly, when to load assets when a page loads.
The preload
attribute can be used on several HTML elements. For example, you can add it to the <link>
element to make browsers initiate an early fetch for your CSS stylesheet.
Don’t use the preload
attribute on your <link>
like this (as some websites recommend):
<link rel="preload" rel=stylesheet href="/css/styles.css" as="style">
Because the code above only preloads your stylesheet, it doesn’t apply it.
Instead, to both preload and apply your stylesheet (as soon as it has preloaded), you can use an inline JS onload
eventhandler on your <link>
element:
<link rel="preload" href="style.css" as="style" onload="this.rel='stylesheet'">
The JS onload
eventhandler will then change the link element’s rel="preload"
attribute to rel="stylesheet"
as soon as it’s done loading.
With the configuration above, browsers that support preload
will start downloading the CSS stylesheet earlier than if you didn’t use the attribute.
Browser support
The preload
attribute isn’t supported in Firefox yet (oddly), but it works in all other modern browsers. You can still use the preload
attribute, but it just won’t prefetch your CSS in Firefox (it will load normally).