How to manage DOM elements

2020-04-11 09:16发布

问题:

I have implemented Infinite scrolling(i.e Load records when the scrollbar reaches the bottom of the div). It works fine but after loading too many records on the page, the page becomes too heavy & causes slow rendering. Actually, I am using this technique as a replacement of a gridview so, how do i manage heavy DOM in this scenario?

回答1:

  1. Reduce the DOM elements to minimum.
  2. Minimize the number of wrappers.
  3. Minimize the acces to the DOM elements, which includes ( yahoo suggestions ):
    • Cache references to accessed elements
    • Update nodes "offline" and then add them to the tree
    • Avoid fixing layout with JavaScript
  4. If there is any computation which can be reduced, like getting the number of rows ( don't calculate it everytime, just add the number of the new rows to the current ), cache it ( memoization wikipedia )

If you have any type of iteration over a collection of DOM elements and you don't use jQuery to iterate, use this (suggestions by JavaScript patterns):

for (var iteration = 0, limit = lengthOfElements; iteration++; iteration < limit)

or

for (var i = myarray.length; i--; )