JavaScript optimization Part 2: Applying styles to elements

Posted by Dmytro Shteflyuk on under JavaScript

This is second part of articles cycle devoted to JavaScript optimization. In this post I’ll cover dynamic elements styling and explore a little HTML-rendering process. Also you will find here some tricks on how to make your applications faster.

Scenario: you have elements in your document and you need to change their color, background, or something else related to theirs style. For example, highlight table rows on mouse over or mark them when corresponding checkbox is checked.

And again I know two ways: using styles or set foreground(or background) color directly from JavaScript. Let’s test them before discussion:

1
2
3
4
var items = el.getElementsByTagName('li');
for (var i = 0; i < 1000; i++) {
    items[i].className = 'selected';
}

The average result is 187 – 291 ms, for the InternetExplorer 6 it is 512 ms, and in Opera 9 it is 47 ms.

1
2
3
4
5
var items = el.getElementsByTagName('li');
for (var i = 0; i < 1000; i++) {
    items[i].style.backgroundColor = '#007f00';
    items[i].style.color = '#ff0000';
}

I got results starting from 282 ms in Opera and ending with 1709 ms in Internet Explorer 6.

Result are clean and easy to understand:

No Method IE 6 IE 7 FF 1.5 FF 2.0 Opera 9
1 element.className 512 187 291 203 47
2 element.style.color 1709 422 725 547 282

Benchmark: Applying styles to elements

You can view benchmark test and get your own results here.

Looks like this is simplest optimization tip, but... there is one issue with Internet Explorer -- page update. Are you remember scenario described in the beginning of chapter, about onmouseover? When you change element's class name, your code is much faster, but the page would not be updated immediately. Look at this example. Try to click "Generate elements" when "element.className" radio button is selected. Then move your mouse pointer over the items, scroll list to the bottom, move mouse again (for slow machines items number would be less than default, for fast ones - greater). Have you noticed, that background changes not so fast as the mouse pointer moves? Now switch selected radio button to "element.style.color". Background changing smoothly, right?

At the bottom of page you see the number of onmouseover events triggered and average time spent to dispatch them. As you noticed, first radio button works two times faster! Why it looks slower? I think it is because when you changed className property Internet Explorer isn't actually updates UI, but placed event in update queue. If you have other ideas, please post comments.

Anybody, who read article up to this place, would probably say: "Hey, guy, you are cheating. Where is the :hover?". I'm hurry up to fix this shortcoming and describing this case right now. First, this thing is not working in the Internet Explorer 6 (and don't ask me "who need it?"). But this is not most difficult problem, performance of this issue is much worse. Even don't want to comment it, just select third radiobutton on previously given page and move your mouse in Internet Explorer 7 and Opera 9 (Firefox works great).

Conclusions

  • Use className when it's possible. It grants you more flexibility and control over site look.
  • If you have many items in your container element, and you need really fast UI, set styles directly through element's style property.

Links to other parts

  • Part 1: Adding DOM elements to document
  • Part 2: Applying styles to elements
  • Part 3: Attaching events
  • Part 4: Multiple anonymous functions (will be published soon)
  • Part 5: Attaching events on demand (will be published soon)
  • Part 6: Element hide and show (will be published soon)
  • Part 7: Elements collection enumeration (will be published soon)

4 Responses to this entry

Subscribe to comments with RSS

said on March 27th, 2007 at 23:25 · Permalink

Критик, спасибо! Я довольно часто задавался вопросом, что лучше использовать и вот выбор стал для меня очевиден. Жду новых статей из данного цикла.

P.S. Вот хотел поделиться. http://htmlbook.ru/css/ – очень хороший справочник для web-разработчика. В конце описания каждого параметра CSS приводится способ доступа к нему из JavaScript

said on February 17th, 2008 at 13:04 · Permalink

ммм, я бы добавил одно уточнение по поводу :hover. Фактически, он становится нужен только для подсветки строк в таблицах (все остальное делается через семантическую верстку и обычный a:hover).

Но для интерфейсов с таблицами, имхо, больше 50 строк на странице вообще делать вредно. В общем, классы скорее рулят, чем нет.

Vitazi
said on March 3rd, 2009 at 22:43 · Permalink

Достаточно странно конечно.. но в opere AC все с точностью да наоборот)) и ховер оказывается самым шустрым)) а вот ClasseName просто жутко тормозит..

Иван
said on March 4th, 2009 at 16:45 · Permalink

По поводу изменения страницы в internet explorer я столкнулся с следующим поведением – страница обновляется позже завершения javascript. Т.е. выполнение оператора javascript вовсе не гарантирует немедленного обновления страницы.

Comments are closed

Comments for this entry are closed for a while. If you have anything to say – use a contact form. Thank you for your patience.