I have a page with a lot of vertical scrolling and thousands of DOM elements. For improving performance, I thought about setting display: none;
to the content of the divs above and below the viewport, that is, the divs which are not visible (while keeping their heights, obviously):
In order to check if my idea makes any sense I searched SO and I found this question. According to the comments and to the accepted answer, the best strategy is do nothing, since display: none;
triggers reflow and may have the opposite effect:
Setting display to none triggers reflow which is completely opposite of what you want if what you want is to avoid reflow. Not doing anything doesn't trigger reflow. Setting visibility to hidden will also not trigger reflow. However, not doing anything a much easier.
However, there is a recent answer (which unfortunately seems more like a comment or even a question) that claims that display: none;
is the current strategy used by sites like Facebook, where the vertical scroll is almost infinite.
It's worth mentioning that, unlike OP's description in that question, each visible div in my site is interactive: the user can click, drag, and do other stuff with the div's contents (which, I believe, makes the browser repainting the page).
Given all these information, my question is: does display: none;
applied to the divs above/below the viewport improve performance or does it worsen performance? Or maybe it has no effect?
The "display: none"
property of an Element removes that element from the document flow.
Redefining that element display property from none to any other dynamically, and vice versa, will again force the change in document flow.
Each time requiring a recalculation of all elements under the stream cascade for new rendering.
So yes, a "display: none"
property applied to a nonzero dimensional and free flow or relatively positioned element, will be a costly operation and therefore will worsen the performance!
This will not be the case for say position: absolute
or otherwise, removed elements form the natural and free document flow who's display property may be set to none and back without triggering e re-flow on the body of the document.
Now in your specific case [see edited graph] as you move/scroll down bringing the 'display: block' back to the following div will not cause a re-flow to the rest of the upper part of the document. So it is safe to make them displayable as you go. Therefore will not impact the page performance. Also display: none
of tail elements as you move up, as this will free more display memory. And therefore may improve the performance.
Which is never the case when adding or removing elements from and within the upper part of the HTML stream!