Search

9/16/2008

High Performance Ajax Applications

High Performance Ajax Applications

If you have control over where your code is going to be inserted in the page, write your init code in a <script> block located right before the closing </body> tag.
Otherwise, use the YUI Event utility’s onDOMReady method
Memoization:
Module pattern


var fn = (function () {
var b = false, v;
return function () {
if (!b) {
v = ...;
b = true;
}
return v;
};
})();

Store value in function object

function fn () {
if (!fn.b) {
fn.v = ...;
fn.b = true;
}
return fn.v;
}

Lazy function definition

var fn = function () {
var v = ...;
return (fn = function () {
return v;
})();
};

Running CPU Intensive JavaScript Computations in a Web Browser
demo
Julien Lecomte’s Blog » The Problem With innerHTML

YAHOO.util.Dom.setInnerHTML = function (el, html) {
el = YAHOO.util.Dom.get(el);
if (!el || typeof html !== 'string') {
return null;
}

// Break circular references.
(function (o) {

var a = o.attributes, i, l, n, c;
if (a) {
l = a.length;
for (i = 0; i < l; i += 1) {
n = a[i].name;
if (typeof o[n] === 'function') {
o[n] = null;
}
}
}

a = o.childNodes;

if (a) {
l = a.length;
for (i = 0; i < l; i += 1) {
c = o.childNodes[i];

// Purge child nodes.
arguments.callee(c);

// Removes all listeners attached to the element via YUI's addListener.
YAHOO.util.Event.purgeElement(c);
}
}

})(el);

// Remove scripts from HTML string, and set innerHTML property
el.innerHTML = html.replace(/]*>[\S\s]*?<\/script[^>]*>/ig, "");

// Return a reference to the first child
return el.firstChild;
};

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);
}

tag: performance

沒有留言: