JavaScript optimization: Applying styles to elements

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

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

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

The result in InternetExplorer 6 is 512 ms, and in Firefox it is 291 ms.

var items = el.getElementsByTagName('li');
for (var i = 0; i < 1000; i++) {
  items[i].style.backgroundColor = '#007F00';
  items[i].style.color = '#FF0000';
}

I got 1709 ms in Internet Explorer 6, and 725 ms in Firefox.

Result are clean and easy to understand:

No Method Internet Explorer 6 Firefox 1.5
1 element.className 512 291
2 element.style.color 1709 725
Applying styles to elements

Looks like this is simplest optimization tip, but… there is one issue with Internet Explorer – page update. Do you remember the scenario described in the beginning of chapter, about onmouseover? When you changed class name of element, your core works much faster, but not page update. Try to click “Generate elements” when “element.className” radio button is selected.

Try to move your mouse cursor over items, scroll list to the bottom, move mouse again (for slow machines items number will be less than default, for fast ones – greater). Did you notice that background follows the mouse cursor? Now change selected radio button to “element.style.color”. Background changed smoothly, right?

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

Comments

Our products