Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery DOM manipulation efficiency - building entire page with JavaScript

I'm going to be starting off with a completely blank page (no elements other than html, head and body) and will then build the page using jQuery. The page contents will be in the form of JSON from an AJAX request. The contents from JSON will not have any HTML. The HTML with content will be built for different sections of the page depending on the structure of the JSON object.

This page will have various sliders, modals and other "dynamic" content.

My question is, will it be faster (lets take IE7 as the lowest common denominator) to build the HTML as one large string (using a string builder which is much faster than standard concatenation) and inject this into the body in a bulk fashion, i.e.

var html = "<div id='content'><p>All markup required for the page, built from the contents of the JSON object</p></div><div id='slider'>...</div>...etc."
$("body").html(html)

And then when that is in the DOM, use jQuery to find and apply plugins to the various dynamic parts, i.e.

$("#slider").sliderPlugin(options);

OR

Would it be better to create each element (or some) as a variable, then append to the body? i.e.

var content = $('<div/>', {id: "content"})
var slider =  $('<div/>', {id: "slider", html="<ul><li>...</li></ul>"}).appendTo(content);
$('body').append(content)

then with this approach I don't have to query the DOM, I only have to do this:

slider.sliderPlugin(options);
like image 863
Fergal Avatar asked Nov 05 '22 10:11

Fergal


2 Answers

I guess building the HTML once is the best way, I vaguely remember reading this somewhere

edit: I read It here with many more jQuery optimizations. a nice and recommended read

like image 166
alonisser Avatar answered Nov 12 '22 17:11

alonisser


The advice I've seen is that it is typically faster to supply a single large chunk of HTML to .html() and then rely on your browser's built-in parser to just do its thing.

However if you're going to be subsequently manipulating individual elements (e.g. adding event handlers, etc) then there's something to be said for creating those elements using the jQuery $('<element>') method.

Also, given an attribute value such as xx"xx (nb: embedded quote marks) it's far more reliable and secure to do:

$('<div>', { attr: foo })

than to do this:

html += '<div attr="' + foo + '"/>';

Since if foo contains special HTML characters you'd have to escape them yourself.

Hence unless your content is really large I'd forget the performance concerns and go for large chunks of HTML when there's static HTML, but use the tag creation methods if you're interposing variable strings.

like image 33
Alnitak Avatar answered Nov 12 '22 15:11

Alnitak