Is there any advantage or improvement to us using the media attribute in the link tag? If so?, then I don't need to use the @media
rule in my CSS, using the media attribute will be enough to set the breakpoints for my web page, right?
An advantage of using the media attribute in a link tag that was not mentioned is that by including styles this way we can avoid CSS render blocking.
Let's say I have a page that the very basic style is set inline, but I also have styles for tablet (768px
) in an external file and some others styles that are only applied on tablets.
I have recorded the rendering process for both cases with media attribute in link tag and without with Google Chrome DevTools. In order to see this working, I have added network throttling to Slow 3G
and CPU slow down to (20x slowndown
)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link href="http://demo.wpthemego.com/themes/sw_emarket/wp-content/cache/wpfc-minified/228b2c494ae153cae7dd875ddf3b1a2f/1503393313index.css" rel="stylesheet">
<link href="https://www.youtube.com/yts/cssbin/player-vflSoLyqv/www-player-webp.css" rel="stylesheet">
<style>
h1 {
background: yellow;
color: black;
font-size: 2rem;
font-weight: lighter;
}
</style>
</head>
<body>
<h1>blocked render</h1>
</body>
</html>
The stats:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link media="(min-width: 768px)" href="http://demo.wpthemego.com/themes/sw_emarket/wp-content/cache/wpfc-minified/228b2c494ae153cae7dd875ddf3b1a2f/1503393313index.css" rel="stylesheet">
<link media="(min-width: 768px)" href="https://www.youtube.com/yts/cssbin/player-vflSoLyqv/www-player-webp.css" rel="stylesheet">
<style>
h1 {
background: yellow;
color: black;
font-size: 2rem;
font-weight: lighter;
}
</style>
</head>
<body>
<h1>Not render blocked under 768px</h1>
</body>
</html>
The stats:
728px
So using media attribute helps us to prevent render blocking and improve the critical rendering path. For further information please read the article in Developers Google Render Blocking CSS