04.11.2015 Views

javascript

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Chapter 20: Best Practices<br />

In this code, an array and an object are created and initialized. Each requires four statements: one to call<br />

the constructor and three to assign data. These can easily be converted to use literals as follows:<br />

//one statement to create and initialize array<br />

var values = [123, 456, 789];<br />

//one statement to create and initialize object<br />

var person = {<br />

name : “Nicholas”,<br />

age : 29,<br />

sayName : function(){<br />

alert(this.name);<br />

}<br />

};<br />

This rewritten code contains only two statements: one to create and initialize the array, and one to create<br />

and initialize the object. What previously took eight statements now takes only two, reducing the<br />

statement count by 75%. The value of these optimizations is even greater in codebases that contain<br />

thousands of lines of JavaScript.<br />

Whenever possible, replace your array and object declarations with their literal representation to<br />

eliminate unnecessary statements.<br />

There is a slight performance penalty for using literals in IE 6 and earlier. These<br />

issues were resolved in IE 7.<br />

Optimize DOM Interactions<br />

Of all the parts of JavaScript, the DOM is without a doubt the slowest part. DOM manipulations and<br />

interactions take a large amount of time because they often require re - rendering all or part of the page.<br />

Further, seemingly trivial operations can take longer to execute because the DOM manages so much<br />

information. Understanding how to optimize interactions with the DOM can greatly increase the speed<br />

with which scripts complete.<br />

Minimize Live Updates<br />

Whenever you access part of the DOM that is part of the displayed page, you are performing a live<br />

update . Live updates are so called because they involve immediate (live) updates of the page ’ s display to<br />

the user. Every change, whether it be inserting a single character or removing an entire section, incurs a<br />

performance penalty as the browser recalculates thousands of measurements to perform the update. The<br />

more live updates you perform, the longer it will take for the code to completely execute. The fewer live<br />

updates necessary to complete an operation, the faster the code will be. Consider the following example:<br />

var list = document.getElementById(“myList”);<br />

for (var i=0; i < 10; i++) {<br />

var item = document.createElement(“li”);<br />

list.appendChild(item);<br />

item.appendChild(document.createTextNode(“Item “ + i));<br />

}<br />

657

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!