Hacker News new | ask | show | jobs
by pg_bot 3021 days ago
There is a different and IMO better way to solve the global scope problem in CSS. Adapted from the Paul Irish method of executing JS you can use data attributes to conditionally write CSS. For example a new user controller would output the controller and action names as data attributes on the body. I then have a separate css file under `assets/users/new.scss` which only contains css for that page. Your Sass code looks something like:

  [data-controller="user_controller"][data-action="new"] {
    .header {
      background-color: blue;
    }
  }
This method keeps you organized and completely removes the biggest problem most people have with CSS.
1 comments

If we're going that way, you might as well include that particular file only on that page.
I would rather have one single request for a large static asset, than multiple small requests for per page based css. In my experience CSS files typically fall in the range 50-100KB. I'd rather not have to pay the perf penalty every time I load a new page considering the typical file size.
For what its worth, this is no longer the case with HTTP/2, which is up and coming for most sites (I hope). I imagine in a few years time this will be gone with the wind (hopefully).

see https://docs.google.com/presentation/d/1r7QXGYOLCh4fcUq0jDdD...

and

https://medium.com/@asyncmax/the-right-way-to-bundle-your-as...