Premasagar Premasagar - 1 year ago 95
CSS Question

Rendering performance: style attributes or classnames and stylesheet rules?

I'm building a data visualisation, and the rendering performance is critical. My question would be relevant to bog-standard HTML, though I happen to be using SVG, with JavaScript.

OK, a hypothetical scenario: say I have 10,000 DOM nodes with a

of "
", and 10,000 DOM nodes with a
of "
". Each node is created by a JavaScript loop. I could either:

  1. Set a
    attribute on each node, specifying the
    of the node:
    <element style="background-color:red;"/>

  2. Set a
    attribute on each node, and then reference that class in an inline style or external stylesheet:

    <head><style>.foo {background-color:red;}</style></head>

    <body><element class="foo"/></body>

The performance of downloading the code is not at all important here - I'm only interested in the browser's rendering performance. I'm also quite aware that style attributes are not usually so useful or semantic in day-to-day website development, but I have a specific use case here.

I am interested in logical answers, but it'd be really useful to hear from anyone has actually tested this or read about someone else's tests (I've searched for information, but found nothing specifically on this).

Thanks for your help!

Answer Source

I've created a performance benchmark for this:

From initial tests in Firefox and Chrome, it looks like it's around three times as fast to create and render elements that use classNames, rather than style attributes. I was quite surprised by that - I wasn't sure, but expected the opposite.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download