Unblocking CSS with Media Queries – Website Performance Optimization

Unblocking CSS with Media Queries – Website Performance Optimization

CSS allows us to scope styles to particular conditions. For example, consider the file we have in front of us. The body rule applies in all conditions. However, when the device is in landscape mode, we apply a special rule to float the menu on the right. Similarly, if someone decides to print the page, we resize the text to use a smaller font size.>>Yeah, media queries are important for a responsive web design, but how does this help us optimize a critical rendering path?>>Great question. First of all, check out the link in the instructor notes to learn about media queries. The web fundamentals slide has a great and detailed explanation of how they work. And to answer your actual question, let’s say I’m rendering a page that’s using this CSS file. We noted the browser would block rendering until it parses all of these styles but intuitively do you think it should block rendering on the print rules?>>Mm, well, I guess if we’re not printing the page then there’s really no reason to block rendering, right?>>Exactly. This is why it makes sense to sometimes split the CSS into multiple files. Let’s give this a try. Our first step is to move our print styles into separate file. Let’s call it Style Print CSS. Next, we add an extra link to our HTML mark up. And here’s the important part, by default the browser assumes that each specified style sheet is render blocking. However, we can also tell the browser when the style sheet should be applied by adding a media attribute with the media query. In this case, sense style-print.css is only used for print, we add media-print.>>Oh, so now when the browser sees a style sheet it knows that it only needs to apply it for printing and hence it doesn’t need to block rendering when we’re loading on the phone. You got it. The browser still downloads both style sheets, but it wouldn’t block rendering on style-print.css. And in this particular case it just means that the browser has to download less data for style.css which would help with the download speed.>>That makes sense. But this is a pretty trivial example. Let’s say I’ve got a much more complicated set of styles with multiple break points. Would this technique help here as well?>>Absolutely, you can specify any media query on the link attribute, and the browser will do the right thing. Once again, check out the article in the instructor notes for directions on how to use media queries.>>Okay, now the page feed recommendations about reducing the number of critical CSS elements makes a lot more sense.>>Glad to hear. let’s do a quick quiz to test your understanding.


2 thoughts on “Unblocking CSS with Media Queries – Website Performance Optimization”

Leave a Reply

Your email address will not be published. Required fields are marked *