<style> tag to inline style=”” attrrib

June 21st, 2012. Tagged: CSS, performance

As you may have noticed, I claim that CSS is bad for performance because:

  1. Most browsers block the very first paint until all screen CSS arrives
  2. Additionally many browsers block rendering until all non-screen (e.g.print) CSS arrives
  3. Sometimes CSS blocks downloads

See "The evil that CSS do" in CSS and the critical path for details.

CSS is the critical path to delivering any UI in the browser. Images arrive whenever, JS can be async.

So any page needs to get CSS out of the way ASAP.

Simple, highly optimized pages (e.g., e.g.) reduce CSS to the bare minimum and then shove it inline in a <style> tag.

ExCeSS

It's a fact of life that there will always be unused CSS, no matter how hard you try to reduce it. (Run PageSpeed for a proof)

Take the simplest CSS: your reset.css

It has stuff like

h1, h2 , h3, ..., abbr, blockquote{ margin:0; ....}

All the HTML tags are in there. But do you have all the tags in the page? Unlikely. So there's excess CSS even at the very base. It usually gets much worse from here. Whole features may or may not be in the page or combined in different ways, but the CSS to handle all combinations is always there, omnipresent.

To style="" attrib

I saw today that Mailchimp has this CSS inliner tool. (Because mail clients often strip <style>). It takes the <style> tags in the markup, strips them and adds style="" attributes where applicable.

I decided to give it for a spin with Facebook like and Google search's HTML. Remember: these are two already highly optimized pages.

Assuming the tool works correctly, the results were pretty impressive.

  • Like: 8,133 bytes from 10,115 (20% reduction, 23% after `gzip -9`)
  • Search: 63,508 from 90,846 (30% reduction, 27% post gzip)

I know, I know what you'll say: inline style="" is an abomination. Should we bring <font> back? What about the cascade? Is this transformation needed on every page view with dynamic content, how's that scalable? What if there's a lot of content with the same class, lot of duplicates?

I know, I know.

But, but... look at the results. 25% reduction of the HTML payload!

With web development moving more and more toward transformations and compilation (css preprocessors, coffee script, monification, etc) it may not be unthinkable.

Back to Earth

On more realistic note, just reduce the CSS to under 2K or thereabouts, inline it in the head, send it with the the first server flush (even before any data fetching) and you'll be in a good place already!

Tell your friends about this post: Facebook, Twitter, Google+

Sorry, comments disabled and hidden due to excessive spam. Working on restoring the existing comments...

Meanwhile, hit me up on twitter @stoyanstefanov