JQuery: $ (template) vs .clone ()

Suppose we have a complex template string (possibly a div containing many other tags ..), and we need to add this HTML node several times to our existing document.

Will it be faster to create HTML nodes from the template each time

 var $html = $(template); // 1st run var $html = $(template); // 2st run ... 

or create them only once, and then clone them:

 var $template = $(template); // init var $html = $template.clone() // 1st run var $html = $template.clone() // 2st run ... 
+8
jquery templates
source share
1 answer

Using a template is likely to be consistently faster for short templates than a clone in all tested browsers except Opera (one test case, equal performance). Thanks to everyone for the test cases.

http://jsperf.com/clone-versus-template

update:

this is a test with a long template and a template built using jQuery:

http://jsperf.com/clone-versus-template/4

this last test shows that the clone method is far superior to the template method in Chrome, Firefox and Opera, but they are equal in IE9

+6
source share

All Articles