jQuery DOM 操作 - 性能比较?
我正在学习使用 jQuery 进行 DOM 操作,并希望了解浏览器性能最佳实践。
假设我有两个 DOM 元素(div、p、ol 等),我希望用户只能看到第一个元素,然后只能看到第二个元素。
我可以:
- 使用replace()
- remove()第一个元素并add()第二个元素
- 隐藏()第一个元素并show()第二个元素
之间的性能差异是什么:
- 1 vs. 2
- 2 vs. 3
- 1 vs . 3
如果元素属于不同类型,是否需要额外考虑性能?或者如果元素是按钮或表单字段?
I am learning DOM manipulation with jQuery and want to understand browser performance best practices.
Say I have two DOM elements (div, p, ol, etc) and I want a user to only see the first element and then only see the second element.
I could:
- Use replace()
- remove() the first element and add() the second element
- hide() the first element and show() the second element
What is the performance differences between:
- 1 vs. 2
- 2 vs. 3
- 1 vs. 3
Are there additional performance considerations if the elements are of different types? Or if the elements are buttons or form fields?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
由于浏览器回流,在 DOM 中删除和添加元素会消耗大量资源,浏览器必须重新渲染部分或全部页面。您希望尽可能避免回流;它们成本高昂。
替换本质上是删除然后添加,因此上述内容适用。
显示和隐藏是最好的,因为它只是向元素添加样式。
您应用这些方法的元素类型也不应该导致上述内容发生变化。
总之,使用
.show()
和.hide()
可以获得最佳性能。Removing and adding elements to the DOM is expensive in terms of resources because of browser reflow, where the browser must re-render part or all of the page. You want to avoid reflows whenever you can; they are costly.
Replacing is essentially a removal then an addition, so the above applies.
Showing and hiding is best, because it is only adding styles to the elements.
The type of elements you're applying these methods too should not lead to a change in the above.
In conclusion, use
.show()
and.hide()
for best performance.基本上,如果您不想隐藏某些内容并稍后再次显示它,那么最好使用 hide() 和 show()。这不会改变 dom 的任何内容,只是改变它的显示方式。
Basically if you wan't to hide something and then show it again later, it is always best to hide() and show(). This won't change anything about the dom, just changes the way it is displayed.