My FeedDiscussionsHeadless CMS
New
Sign in
Log inSign up
Learn more about Hashnode Headless CMSHashnode Headless CMS
Collaborate seamlessly with Hashnode Headless CMS for Enterprise.
Upgrade ✨Learn more

Considerations for bundling/serving CSS

Tommy Hodgins's photo
Tommy Hodgins
·Oct 6, 2018
  • Avoid using @import in CSS at all costs, it blocks parsing the rest of your styles while it goes off to make more network requests for the imported files.

  • The browser doesn't really care about the number of stylesheets used, after CSS is parsed the browser it treats all CSS like one giant stylesheet anyway. Feel free to use as many stylesheets as you want. CSS has performance limitations in other areas, but the number of stylesheets isn't one of them.

  • Individual CSS files can be cached by the browser, where inline styles cannot be cached. A cached stylesheet loads much faster than one that has to be transferred over a network each time.

  • The best way to add a stylesheet to HTML is via the <link> tag.

  • CSS can also be embedded in a <style> tag inside HTML, but it's a tradeoff: you save a network request for the stylesheet, but forfeit the chance for the browser to cache that stylesheet.

  • You can add styles to HTML with Javascript via the CSSOM, or with <link> or <style> tags in the DOM, or by setting the style property. Adding CSS with JavaScript is the least desirable option, so a good rule of thumb here is to do anything in CSS that can be done in CSS.

  • Depending on whether you have HTTP/2 enabled on your server, it may be more efficient to send many small files versus sending one large file. Bundling multiple files into one might not be the most efficient way your server is configured to send files. The answer will depend on your server configuration, and the number and size of the files you are serving.

  • If you want to bundle multiple files into one CSS file, you don't really need a special bundling tool. Adding the contents of the stylesheet files together into one file (concatenating the files), paying attention to the order they are loaded in (to respect the cascade) is all that's required. It could be as simple as this command:

$ cat *.css > bundle.css
  • If you want to reduce bandwidth, enable GZIP compression on your server. Repeated parts of files compress well, so the more consistent your code formatting, usually the better the compression.

  • If you want to reduce filesize, the CSS minifier I recommend is CSSnano, but whether you minify your CSS or not—keep in mind that the savings here are tiny so don't stress over it, and don't waste too much time if it doesn't work. Failing to optimize just 1 image on your site might wipe out any benefit you can get by squeezing all the extra space out of your CSS.