Reputation: 2168
I'm trying out rel=preload
for the first time, using it for a couple of stylesheets. Here is the code in question:
<link rel="preload" href="css/styles.css" as="style">
<link rel="preload" href="//allyoucan.cloud/cdn/icofont/1.0.0beta/css/icofont.css" crossorigin="anonymous" as="style">
I'm testing in Chrome 61, and I can see that the stylesheets are downloaded as expected, however they're never actually applied, and I get the message on the console saying that a preloaded resource isn't being used.
If I remove the rel=preload
in favour of just rel=stylesheet
, then it works perfectly fine.
Is there something I'm missing?
Upvotes: 63
Views: 51273
Reputation:
The accepted answer is correct but not very clear. For one file, you need 2 lines, and not one:
<link rel="preload" href="css/styles.css" as="style">
<link rel="stylesheet" href="css/styles.css">
I used this approach mostly because of css background images. Apparently this will speed up the loading.
You can see this approach in a similar fashion for google fonts links:
<link rel='preconnect' href='https://fonts.googleapis.com'>
<link href='https://fonts.googleapis.com/css2?family=Source+Serif+Pro:wght@300&family=Source+Sans+Pro:wght@300;400;600&display=swap' rel='stylesheet'>
It's also useful for fonts. See Mozilla Docs
Upvotes: 7
Reputation: 12964
Technically, you can specify multiple values for rel
attribute. Something like this should do the job, without writing 2 lines per stylesheet:
<link rel="preload stylesheet" href="/css/styles.css" as="style" type="text/css" crossorigin="anonymous">
You can verify this using Lighthouse. This was result on my browser (there was no chained request as stylesheet was preloaded, and was properly applied):
Upvotes: 22
Reputation: 900
What do you think about this approach:
<link rel="preload" href="style.css" as="style" onload="this.rel='stylesheet'">
Resource: https://www.filamentgroup.com/lab/async-css.html
Upvotes: 59
Reputation: 30518
You need to have 2 lines for each one with rel=stylesheet and one with rel=preload. As preload is just fetching it and not applying.
However you will probably not notice much performance improvement as it hits one line just before the other.
The better option is to inline the css (see here) that is seen above the fold then use javascript to add in the in the css file on page load (see here).
Upvotes: 44