high-performance dom scripting

16
Chapter 3: DOM Scripting Stoyan Stefanov Yahoo! Search Bayjax – April 13, 2010

Upload: stoyan-stefanov

Post on 15-Jul-2015

4.466 views

Category:

Technology


0 download

TRANSCRIPT

Chapter 3: DOM Scripting

Stoyan StefanovYahoo! Search

Bayjax – April 13, 2010

Tonight: DOM is slow

• How slow?• Why is it slow?• What to do about it?

How slow?

// bad

var count = 0;

for (; count < 15000; count += 1) {

document.getElementById('here').innerHTML += 'a';

}

// DOM access = (1 get + 1 set) * 15000

// better

var count = 0, content = '';

for (; count < 15000; count += 1) {

content += 'a';

}

document.getElementById('here').innerHTML += content;

// DOM access: get + set

How bad are we talking about?

Why slow?

The bridge

DOMlandECMAland

The browser

Dynatrace

Dynatrace

Speed tracer

bodystyle.color = 'red';tmp = computed.backgroundColor;bodystyle.color = 'white';tmp = computed.backgroundImage;bodystyle.color = 'green';tmp = computed.backgroundAttachment;

bodystyle.color = 'red';bodystyle.color = 'white';bodystyle.color = 'green';tmp = computed.backgroundColor;tmp = computed.backgroundImage;tmp = computed.backgroundAttachment;

What to do about it?

10 commandments

• Don’t touch the DOM• Cache DOM references in local vars• Use selectors API• Cache the length when looping collections• Update the DOM offline• Batch style changes• Don’t ask for layout info excessively• Minimize reflow areas• Use event delegation (see Y.delegate())• Don’t touch the DOM

Etcetera• Blog: www.phpied.com• Email: [email protected]• Twitter: @stoyanstefanov

YSlow 2.0