开发者

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 background-color of "red", and 10,000 DOM nodes with a background-color of "green". Each node is created by a JavaScript loop. I could either:

  1. Set a style attribute on each node, specifying the background-color of the node: <element style="background-color:red;"/>
  2. Set a class attribute on each node, and then reference t开发者_如何转开发hat 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!


I've created a performance benchmark for this: http://jsperf.com/style-element-vs-attr

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.


I would be extremely surprised if there is a significant difference (and even more surprised if it ever mattered) but if there was one it would be in IE so bench that.

That said, the conditions you are testing are so edge case that I do not think you should be abusing your markup to attain a small-to-insignificant performance benefit in the event that inline was faster. Class based CSS is immeasurably better for the purposes of development and maintenance and semantics and you should avoid inline styles at all costs.


If you say, each node is created within a JavaScript loop, isn't that already demanding on browser performance(JavaScript Engine)?

Somehow, I'd be slightly more comfortable setting the colors via JavaScript itself. Say, $(this).css('color','red'); rather than adding a class which then requires the browser to lookup the computed styles available at the time the script is running and then render/re-render the color change.

I'm not sure if I'm completely right, just an opinion.


After compare the result, I'll stick for using CSS-in-JS solutions, I've tried many, and finally using this lib:

https://github.com/cssobj/cssobj

It's create and update CSS Rules from JS, and it's small in size.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜