简体   繁体   English

操纵隐藏的DOM元素会影响性能吗?

[英]Does manipulating a hidden DOM element affect performance?

I have a page with 3 charts that are rendered via HighCharts. 我有一个页面,其中有3个图表通过HighCharts呈现。 Most users will access this page via a tablet. 大多数用户将通过平板电脑访问此页面。 The charts are all "live data" charts, so they update every second with new data. 图表都是“实时数据”图表,因此它们每秒都会使用新数据进行更新。 At a given time, only one chart is visible. 在给定时间,只能看到一个图表。

When the charts are hidden (display:none), but their HTML is still being updated every second, does that affect performance? 隐藏图表(显示:无),但他们的HTML仍然每秒更新一次,这是否会影响性能? Would it make a difference if I removed the chart's containing element from the DOM while it's hidden, and then appended the element back in when showing the chart again? 如果在隐藏时从DOM中删除图表的包含元素,然后在再次显示图表时将元素重新附加,是否会有所不同? The chart would still be updated every second when it was removed from the DOM, but it wouldn't actually be a part of the DOM. 当图表从DOM中删除时,图表仍会每秒更新一次,但实际上它不是DOM的一部分。

When the charts are hidden (display:none), but their HTML is still being updated every second, does that affect performance? 隐藏图表(显示:无),但他们的HTML仍然每秒更新一次,这是否会影响性能?

Yes, it affects the performance even if it's hidden. 是的,它会影响性能,即使它是隐藏的。 For example $('#fooElement') inside your script would still go through the DOM trying to find the element. 例如,脚本中的$('#fooElement')仍会通过DOM尝试查找元素。 However when the element is updated while hidden it doesn't have to be rendered by the browser, so it's less costly. 但是,当元素在隐藏时更新时,它不必由浏览器呈现,因此成本更低。

Would it make a difference if I removed the chart's containing element from the DOM while it's hidden, and then appended the element back in when showing the chart again? 如果在隐藏时从DOM中删除图表的包含元素,然后在再次显示图表时将元素重新附加,是否会有所不同?

If you remove it from the DOM you would have to construct it when the user tries to view it. 如果从DOM中删除它,则必须在用户尝试查看它时构造它。 This is IMHO more costly than to leave it in the DOM. 这是恕我直言,而不是把它留在DOM中。 Another thing is that you can just ignore the updates until it's shown. 另一件事是你可以忽略更新,直到它显示出来。 When the chart is about to be displayed just call for a refresh and update it in the DOM with new data and show it afterwads. 当即将显示图表时,只需调用刷新并使用新数据在DOM中更新它并将其显示为Afterwads。 This is of course less resource costly than to do the same plus constructing it every time. 这当然比每次构建它更加耗费资源。

TL;DR Update only elements which are shown. TL; DR仅更新显示的元素。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM