日期:2014-05-16 浏览次数:20426 次
7.Client Pattern
// antipattern for (var i = 0; i < 100; i += 1) { document.getElementById("result").innerHTML += i + ", "; } // better - update a local variable var i, content = ""; for (i = 0; i < 100; i += 1) { content += i + ","; } document.getElementById("result").innerHTML += content;? ? In the next snippet, the second example (using a local variable style) is better, although it requires one more line of code and one more variable:
// antipattern var padding = document.getElementById("result").style.padding, margin = document.getElementById("result").style.margin; // better var style = document.getElementById("result").style, padding = style.padding, margin = style.margin;?
document.querySelector("ul .selected"); document.querySelectorAll("#widget .class");?? These methods accept a CSS selector string and return a list of DOM nodes that match the selection. The selector methods are available in modern browsers (and in IE since version 8) and will always be faster than if you do the selection yourself using other DOM methods. Recent versions of popular JavaScript libraries take advantage of the selector APIs, so you should make sure you use an up-to-date version of your preferred library.
// antipattern // appending nodes as they are created var p, t; p = document.createElement('p'); t = document.createTextNode('first paragraph'); p.appendChild(t); document.body.appendChild(p); p = document.createElement('p'); t = document.createTextNode('second paragraph'); p.appendChild(t); document.body.appendChild(p);? ? A better version will be to create a document fragment, update it “offline,” and add it to the live DOM when it’s ready. When you add a document fragment to the DOM tree, the content of the fragment gets added, not the fragment itself. And this is really convenient. So the document fragment is a good way to wrap a number of nodes even when you’re not containing them in a suitable