Better Performance, Empty Elements Or Create And Destroy With Javascript?

前端 未结 4 830
误落风尘
误落风尘 2020-12-10 09:34

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 exampl

4条回答
  •  北海茫月
    2020-12-10 09:45

    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:

    1. Showing existing hidden element
    2. innerHTML from array + join
    3. innerHTML from string concatenation
    4. Detach + append existing DOM node
    5. Cloning of DOM nodes
    6. Creation of fresh DOM nodes

    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.

提交回复
热议问题