csswizardry / ama

Ask me anything!
57 stars 4 forks source link

Multiple Media Query Stylesheets or 1 Big Stylesheet #46

Closed Cofflescotch closed 5 years ago

Cofflescotch commented 6 years ago

Hi there, I asked the same question on Stack Overflow but I figured I need an expert's opinion on this.

Using an external css grid-work is beneficial but the load times are intense especially with the breakpoint media queries. What are the pros and cons to loading multiple stylesheets, 1 main one with general grid-layout css, and then other stylesheets to accommodate for the media query breakpoints for that css grid layout? If this is a good idea then this could be the next new standard for optimized css loading.

Example 1: (using 1 stylesheet)

<link href="style.css" rel="stylesheet">
.col-md-6 {
    width: 50%;
}
@media all and (max-width: 768px) {
    .col-md-6 {
        width: 100%;
    }
}

Example 2: (using 2 stylesheets)

<link href="style.css" rel="stylesheet">
.col-md-6 {
    width: 100%;
}

<link href="style-768.css" rel="stylesheet" media="all and (max-width: 768px)">
.col-md-6 {
    width: 100%;
}

From what i can tell here on Googles Developer docs a stylesheet that is only loaded when needed (i.e. at max-width: 768px) is only seen as 'render-blocking' if it is used. When it is not used then this whole stylesheet can possibly be skipped over and dramatically reduce the initial load of the css needed at that time.

Is this a good practice? seems like cutting out 2/3s of a css grid system by relocating media query blocks has serious benefits, but perhaps that is canceled out by the DOM needing to get more than one CSS doc?

nicodeclercq commented 6 years ago

From what CSS Wizardry wrote on ITCSS, I'll stay with one stylesheet. Cutting media queries in other files would broke the pattern and make components/objects having different definition files which would make the maintenance harder and so the files growth much much faster. If this cutting could be done at build time by webpack or any tool, this could be great but from now I'll personnally stick to one file...

csswizardry commented 5 years ago

Sorry for taking so long to respond to this! My bad.

The answer to this is… it depends.

If you’re able to simply, quickly, and consistently compile out a handful of separate stylesheets (say, to pick a number, fewer than 10), then loading them all as separate files based on media query may have some great performance benefits—browsers will only load the ones they need immediately on the critical path. For more in-depth information, see CSS and Network Performance.

To @HermineF’s point, as long as everything still renders properly, then we don’t really mind if the shipped CSS doesn’t match the Inverted Triangle.