Following instructions from Mozilla.org I created this very simple example for CSS preloading but it just doesn’t work.
Current Behavior: The Background is white
Expected Behavior: The Background should be red, and a weird message is displayed in the console.
cssPreloadTest3.html:
<html>
<head>
<meta charset="utf-8">
<title>CSS preload example</title>
<link rel="preload" href="cssPreloadTest2.css" as="style">
</head>
<body>
<h1>bouncing balls</h1>
</body>
</html>
cssPreloadTest2.css:
body {
background: red;
}
The weird message in the console says:
The resource at “https://…./cssPreloadTest2.css” preloaded with link preload was not used within a few seconds. Make sure all attributes of the preload tag are set correctly.
Of course if you change the <link>
to a standard css import like this it works fine:
<link rel="stylesheet" href="cssPreloadTest2.css">
¿How can I make this work?
2
Answers
Preload
<links>
are not meant to replace the standard<link rel="stylesheet">
, they just tell the browser to preload the assets. So you you still have to include the styles in any of the normal ways (either<link rel="stylesheet">
or@include
).They should probably clarify that in the Mozilla website...
Basically, preload means that the browser has to download a resource before it’s gonna use by the browser for some purpose. When you preload CSS, it means that the browser will start downloading your resource ASAP and apply it when it found a suitable command for that for example when it finds
<link>
tag for the stylesheet it will apply it instantly and hence first contentful paint will be improved.There is also a concept here. If you download your CSS as a non-critical resource then you don’t need to include
<link>
tag.Syntax:-
But this thing is suitable only for deferring non-critical CSS. But for critical CSS you can include an internal stylesheet i.e. in
<style>...</style>
tags.Read more about it here – https://web.dev/defer-non-critical-css/