24. How to handle long running JavaScript processes (2/2) function doSomething (callbackFn) { // Initialize a few things here... ( function () { // Do a little bit of work here... if ( termination condition ) { // We are done callbackFn(); } else { // Process next chunk setTimeout(arguments.callee, 0); } })(); }
28. Document tree modification Using innerHTML var i, j, el, table, tbody, row, cell; el = document.createElement( "div" ); document.body.appendChild(el); table = document.createElement( "table" ); el.appendChild(table); tbody = document.createElement( "tbody" ); table.appendChild(tbody); for (i = 0 ; i < 1000 ; i++) { row = document.createElement( "tr" ); for (j = 0 ; j < 5 ; j++) { cell = document.createElement( "td" ); row.appendChild(cell); } tbody.appendChild(row); } var i, j, el, idx, html; idx = 0 ; html = []; html[idx++] = "<table>" ; for (i = 0 ; i < 1000 ; i++) { html[idx++] = "<tr>" ; for (j = 0 ; j < 5 ; j++) { html[idx++] = "<td></td>" ; } html[idx++] = "</tr>" ; } html[idx++] = "</table>" ; el = document.createElement( "div" ); document.body.appendChild(el); el.innerHTML = html.join( "" ); ( much faster on all A-grade browsers) Warning: See http://www.julienlecomte.net/blog/2007/12/38/
29. Document tree modification Using cloneNode var i, j, el, table, tbody, row, cell; el = document.createElement( "div" ); document.body.appendChild(el); table = document.createElement( "table" ); el.appendChild(table); tbody = document.createElement( "tbody" ); table.appendChild(tbody); for (i = 0 ; i < 1000 ; i++) { row = document.createElement( "tr" ); for (j = 0 ; j < 5 ; j++) { cell = document.createElement( "td" ); row.appendChild(cell); } tbody.appendChild(row); } var i, el, table, tbody, template, row, cell; el = document.createElement( "div" ); document.body.appendChild(el); table = document.createElement( "table" ); el.appendChild(table); tbody = document.createElement( "tbody" ); table.appendChild(tbody); template = document.createElement( "tr" ); for (i = 0 ; i < 5 ; i++) { cell = document.createElement( "td" ); template.appendChild(cell); } for (i = 0 ; i < 1000 ; i++) { row = template.cloneNode(true); tbody.appendChild(row); } (faster on all A-grade browsers – sometimes much faster) Warning: expando properties/attached event handlers are lost!
30.
31.
32. Limit the number of event handlers (2/2) YAHOO.util.Event.addListener( "container" , "click" , function (e) { var el = YAHOO.util.Event.getTarget(e); while (el.id !== "container" ) { if (el.nodeName.toUpperCase() === "LI" ) { // Do something here... break; } else { el = el.parentNode; } } });