Unless you’re using something like Tailwind CSSthe stylesheet files are one of the most expensive resources that your application is loading.
Essentially, you would use the
<link> element to link to your website’s stylesheets. Here’s an example.
<link href="/styles/app.css" rel="stylesheet">
As you can tell, the
<link> element accepts a few of the attributes here. Mainly the
href attribute is used to provide the path to the stylesheet that the document intends to load and the
rel attribute is used to denote the “Relationship” between the element and the containing document.
Here, in this case, the
rel is “Stylesheet” which means the resource specified will be treated as a stylesheet by the document.
Now, this works perfectly fine but consider a scenario where down the road, your application grew significantly and at this point, you want to segregate this “monolith” stylesheet into smaller chunks. For instance, you would divide the stylesheet into mobile.css and tablet.css to place the device-specific CSS in there and load them like so.
<link href="/styles/app.css" rel="stylesheet"> <link href="/styles/mobile.css" rel="stylesheet"> <link href="/styles/tablet.css" rel="stylesheet">
Okay so, we segregated the CSS to device-specific chunks and now we only want to load these stylesheets based on the device the application is being loaded. How do you do it? Well, that’s where another attribute called
media comes into the picture.
<link> element also accepts a
media attribute. The purpose of this attribute is to add some sort of condition to the loading of the stylesheet by providing a media type or query to it.
So, for instance, if we only want to load the
/styles/tablet.css files on their respective viewports, here’s how we can do it.
<link href="/styles/app.css" rel="stylesheet"> <link href="/styles/mobile.css" rel="stylesheet" media="screen and (max-width: 640px)" > <link href="/styles/tablet.css" rel="stylesheet" media="screen and (max-width: 879px)" >
Now, the resources will then only be loaded if the media condition is true. As you can tell, this can improve the performance of your app significantly since the browser will only load the stylesheets based on the matched conditions instead of loading everything all at once.
Loading printer-specific CSS
If you have styles that target special devices such as printers, you can load the respective stylesheet file for that using the
media attribute like so.
<link href="/styles/print.css" rel="stylesheet" media="print" >
Loading CSS based on dark / light mode
If your application has got a dark mode and there are dark mode specific stylesheets, you can control that using the
media elements as well.
<link href="/styles/app.css" rel="stylesheet"> <link href="/styles/dark.css" rel="stylesheet" media="(prefers-color-scheme: dark)" >
As you can tell, in this case, we can use the
prefers-color-scheme media feature to conditionally load
/styles/dark.css when the dark mode is enabled.