// antipattern if (navigator.userAgent.indexOf('MSIE') !== −1) { document.attachEvent('onclick', console.log); } // better if (document.attachEvent) { document.attachEvent('onclick', console.log); } // or even more specific if (typeof document.attachEvent !== "undefined") { document.attachEvent('onclick', console.log); } 5
DOM references to local variables and working with the locals • Using selectors API where available • Caching the length when iterating over HTML collections (see Chapter 2) 7
= 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; 8
// cloneNode(true) if the children of the node should also be cloned, or false to clone only the specified node. https://developer.mozilla.org/en-US/docs/Web/API/Node/cloneNode // work with the clone... // when you're done: oldnode.parentNode.replaceChild(clone, oldnode); 13
• Use event.target to check the target node • Pros ◦ reduce event listeners • Cons ◦ hard to find the event listener from browser developer tool • Demo ◦ http://codepen.io/anon/pen/vLqvaV 16
single top level event listener ◦ https://facebook.github.io/react/docs/interactivity-and-dynamic-uis.html#under-the-hood- autobinding-and-event-delegation 17
onmessage = function (event) { document.body.innerHTML += "<p>message from the background thread: " + event.data + "</p>"; }; // Output message from the background thread: hello there message from the background thread: halfway there, `tmp` is now 3749999975000001 message from the background thread: all done 19 // my_web_worker.js var end = 1e8, tmp = 1; postMessage('hello there'); while (end) { end -= 1; tmp += end; if (end === 5e7) { // 5e7 is the half of 1e8 postMessage('halfway there, `tmp` is now ' + tmp); } } postMessage('all done');
tag) • Often JSON wrapped in a function call • https://zh.wikipedia.org/wiki/JSONP var script = document.createElement("script"); script.src = “http://remote.org/getdata.php?callback=myHandler”; document.body.appendChild(script); // Output of http://example.org/getdata.php?callback=myHandler myHandler({“hello”: “world”}); 22