I am using JQuery to append large amounts of text inside a tag. I find the more text currently within the tag the slower appending is, and for large amounts of text it is too slow.
Is there a more efficient way to append text? Such as for instance creating dummy child tags and setting the content of them rather than appending to the parent?
Use DOM DocumentFragments to append a bunch a node, and take a look on Nicholas Zakas presentation in slideshare "writing-efficient-javascript"
As I have been testing my site, I have noticed that
.innerHTML
is far quicker than jQuery's append methods. This is deprecated though and support may dwindle and die in future browsers. That said thebgcolor
attribute still works and I remember being told that was being deprecated about a decade ago. Don't append scripts with the html fragment either as they need eval'ing (jQuery appears to do this automatically leading to slow times whereas withinnerHTML
you have to do it manually if needed). Eval is dead slow don't use it if possible. Again as previously mentioned joining an array is more efficient than string concatenation. Use variables to point to DOM nodes (i.e.var this = document.getElementById("YourDomNode")
then work withthis
where needed instead of repeating thedocument.getElementById
statement). Declaring variables outside of a function allows them to be accessible from any function. Please note this is client side script so the variable value is a unique reference for each user. Doing that highly repeated strings can reduce file sizes depending what your doing. If you absolutely have to load in your JavaScript inline as part of your html fragments try this:The above code will make the DOM changes visible before all the scripts are eval'd. This isn't multi-threading though so be careful of its use. Far better to use attributes for event handlers (onclick, onchange etc.)
Finally before manipulating an element in the dom set the style to display:none, manipulate it then set the style back to display:inline (inline is default for some common elements) or wahtever it was previously.
This is just a quick mental dump of some tactics ive used so any input / derision of bad practice is welcome.
Check this presentation and this one too: jQuery Anti-Patterns
And in general:
Instead of appending multiple times, store each string in array and join the array when you append it to.