This is a good tweet from Harry:
I like it because, as he says, it’s the correct way to think about it. It helps form a mental model of how websites work.
Just to spell it out a bit more…
/*
Just because I'm in the CSS, doesn't mean I'll load!
In order for `myfont.woff2` to load, a selector needs to
set `font-family: 'MyWebFont';` AND something in the DOM
needs to match that selector for that file to be requested.
*/
@font-face {
font-family: 'MyWebFont';
src: url('myfont.woff2') format('woff2');
}
/*
Just because I'm in the CSS, doesn't mean I'll load!
In order for `whatever.jpg` to load, the selector
`.some-element` needs to be in the DOM.
*/
.some-element {
background-image: url(whatever.jpg);
}
It’d be nice if resources declared in the CSS didn’t load until used by the DOM or until the browser was idle. That way if an element is added dynamically via JavaScript, there’s a good chance the associated resources have already been downloaded.
Then again, I guess this doubles as a protective measure in the event of loads of unused CSS, to save on unnecessary network requests. Could maybe be a thing that developers could be allowed to control?
This begs the question whether tools like Purge CSS are really necessary on any but the absolute largest sites. The extra weight of loading CSS for the entire site on the first page load seems so negligible, that I see no reason not to do it.
Yes, because CSS selectors have a performance impact, most noticeable on older, slower devices/computers. This can even affect battery life on some devices, so it does help to trim out CSS that’s not being used.
Have you seen the output of Tailwind?