I'm refactoring some old JavaScript code and there's a lot of DOM manipulation going on.
var d = document;
var odv = d.createElement("div");
odv.style.display = "none";
this.OuterDiv = odv;
var t = d.createElement("table");
t.cellSpacing = 0;
t.className = "text";
odv.appendChild(t);
I would like to know if there is a better way to do this using jQuery. I've been experimenting with:
var odv = $.create("div");
$.append(odv);
// And many more
But I'm not sure if this is any better.
Answer
here's your example in "one" line.
this.$OuterDiv = $('')
.hide()
.append($('
')
.attr({ cellSpacing : 0 })
.addClass("text")
)
;
Update: I thought I'd update this post since it still gets quite a bit of traffic. In the comments below there's some discussion about I put together a small benchmark, and here's roughly the results of repeating the above options 100,000 times: jQuery 1.4, 1.5, 1.6 jQuery 1.3 jQuery 1.2 I think it's no big surprise, but Update 2 Updated for jQuery 1.7.2 and put the benchmark on JSBen.ch which is probably a bit more scientific than my primitive benchmarks, plus it can be crowdsourced now!$("
$("")
vs $(document.createElement('div'))
as a way of creating new elements, and which is "best". Chrome 11 Firefox 4 IE9
420ms 650ms 480ms
createElement 100ms 180ms 300ms Chrome 11
3800ms
createElement 100ms Chrome 11
3500ms
createElement 100msdocument.createElement
is the fastest method. Of course, before you go off and start refactoring your entire codebase, remember that the differences we're talking about here (in all but the archaic versions of jQuery) equate to about an extra 3 milliseconds per thousand elements.
No comments:
Post a Comment