Dynamic range creation
How to create dynamic tags?
$("<img />").attr({ id: "image-1", src: "/images/flower.png", }).appendTo("#" + imgContainer); It will create <img src="/images/flower.png" id="image-1" />
I want to create a <span> tag around an <img> .
i.e. <span><img src="/images/flower.png" id="image-1" /></span>
DOM operations are so expensive; just prepare the markup you are using and then add it as needed!
//Before: $("<img />") //#1, create an element outside of the tree .attr({ //#2? change its attributes id: "image-1", src: "/images/flower.png" }) .appendTo("#" + imgContainer) //#3, add the element to DOM .wrap("<span />"); //#4, create and add another element to DOM //After: $('<span><img src="/images/flower.png" id="image-1"></span>') //#1 .appendTo("#" + imgContainer); //#2 Here is a jsperf test case that leads to ~ 5K ops / sec for the first case and ~ 14K for the latter (in my pretty decent box).
This is also not a premature optimization. If you, for example, have an ajax-filled table 7x10, and you create each cell separately ... and wrap them in <tr> elements ... and then add it to the table, add extra overhead. Manage the string and your script will be at least 80 times faster!
Another aspect to keep in mind is that jsperf explicitly measures only javascript performance. If you manipulate a table, its contents will be even more aggressively redrawn / repainted .