Reputation: 12275
What would be better for performance, having many hidden elements on a page, or creating them and destroying them as they are needed with javascript upon request. For example, when something is clicked the element is first created and then shown. When it is closed it is then destroyed. Would that be better than having hidden elements scattered among the page?
Upvotes: 3
Views: 2585
Reputation: 31173
IMHO you should do another kind of consideration, since is obvious that page load speed is affected by it's size in term of kb.
How to calculate web page size ?
what is the maximum size?
so, your problem is not properly the number of dom elements, you have a lot of things to do before care of hidden elements number! ;) hope this help
REFERENCE:
TOOLS
Upvotes: 1
Reputation: 62648
You're generally going to get the best on-click performance just showing/hiding elements, but that comes at the cost of a bigger initial page load. If you're using jQuery, you can also use detach() to remove an element from the DOM graph without destroying it, so you can re-attach it elsewhere, which is less expensive than destroy/create.
Generally speaking, in order of performance from best to worst:
If you need to generate complex content on the fly, you might look at a Javascript templating tool like handlebars.js - it'll let you define templates, then create markup from those templates + some passed in object that you can then assign via innerHTML. It makes for a very quick and very efficient way to manage dynamic clientside content.
Upvotes: 3
Reputation: 130817
Creating and destroying DOM elements is about the slowest operation you could do in JavaScript, especially in IE. Having many hidden elements will take up more memory and will probably take a bit longer to load initially, but think of it as a cache: you're caching these elements for later use, and just reusing them when you need them, instead of creating and destroying them on the fly.
However, if you aren't doing this on a very large scale (hundreds/thousands of elements), it probably won't matter. The time it takes to create or destroy a single DOM element is negligible, so if that's your case, do whatever would be easier for you.
Upvotes: 1
Reputation: 86505
I'd imagine it depends in part on how complex the elements are, and in part on what you mean by "performance". The more complex the element, the more code has to run to create it, and the longer it'll take to create. Thus, hiding the element in the page would probably make it appear faster, but at the cost of a bigger page (and more DOM to sift through), which could slow things down a bit overall.
Upvotes: 6