views:

63

answers:

1

Similar to this question: http://stackoverflow.com/questions/337352/jquery-build-html-in-memory-rather-than-dom

I have a

var $container = $("#container");

I also have:

jQuery.fn.somedomedits = function(expr) {
    return this.each(function() {
     var $self = $(this);
     $self.find(".adsf").append("<div></div>");
     // A lot more complex dom insertions like this
    });
};

Right now I'm doing:

$container.somedomedits().somemoredomedits();
// The somemoredomedits method is a similar plugin to the first one.

Just doing it this way changes DOM directly.

so then I did:

var $editeddom = $container.somedomedits().somemoredomedits();
$containerwrapper.html($editeddom);

Is that the correct way to do this?

I see no speed improvements in Firebug/fox, not sure if it would benefit other browsers.

Thanks

+2  A: 

This code is slower

var $editeddom = $container.somedomedits().somemoredomedits();
$containerwrapper.html($editeddom);

because it's doing the same as the

$container.somedomedits().somemoredomedits();

plus assign variable and run one extra method (html()).

This would be faster if you were creating elements on-the-fly and inserting them to DOM tree after the whole structure is ready, but if you are getting elements out of DOM with the jQuery selector you get an object which still "points out" DOM. Assigning that to variable doesn't make it clone automatically.

You could clone this object and then run modification on the clone and after you are done replace the content but you should check first if cloning would be faster then what you are losing working on DOM directly.

// clone part of DOM
// .clone(true) clones event handlers as well if you don't need it
// you can just run .clone()
var items = $(selector).clone(true);

// perform your complex operations
items.somedomedits().somemoredomedits();

// replace part of DOM with modified clones
$(selector).replaceWith(items);
RaYell
Do `$editdom = $container.clone(true);` and *then* the manipulations on `$editdom`.
Boldewyn
Ahah. Thanks! Cloning and then editing increased performance several fold, thanks a lot.
Jourkey
One extra question. Why clone(true) rather than just clone()?
Jourkey
You should use clone(true) only if you have events attached to elements you want to clone. This way cloned elements will still have events hooked.
RaYell