What exactly updates when the DOM is manipulated

白昼怎懂夜的黑 提交于 2021-01-27 06:51:08

问题


I am trying to understand exactly what is updated with the regular DOM after a DOM manipulation.

Suppose we have the DOM below and I use javascript to delete the li with the class blue.

Does this mean that the browser looks at the parent of class blue (eg: id of list 1) and re-renders that DOM node including all the children (minus class blue) and then repaints the whole page based on any css rules?

I would think that would be the process but I wasn't sure and can't find any concrete examples anywhere.

 <div>
   <ul id="list1">
     <li> red </li>
     <li class="blue"> blue </li>
     <li> green </li>
    </ul>
    <ul id="list2">
      <li> orange </li>
      <li> gray </li>
      <li> brown </li>
    </ul>
 </div>

回答1:


That's not all that easy, and this is because you are probably not quite understanding how the DOM update + rendering process works.

The DOM is just a javascript object, like any other.

When you do DOM manips, it's really just like if you did modify a plain-object's properties (a complex one, but still).

Some of these manips may indeed dirty the page's layout and rendered frame, but in general browsers will wait until they really have to perform the repaint operation before triggering both these algorithms. This means that these algorithms won't be triggered at every individual DOM manipulation.

So to answer the question, when the DOM is manipulated, you are changing a js object's properties and possibly setting a flag letting know both the layout recalc and the renderer that they will have to kick in at next screen refresh.

When these layout recalc (a.k.a reflow) and repaint operations actually kick in is not tied by any specs, and it is the very place that most browsers will try to optimize and hence it's hard to have a definitive word on how these work everywhere. (Though it is specified that in some cases reflow should kick synchronously).
But we can assume that if nothing renderable has changed, these will at least be short-cut.

For instance, if in your example #list1 had its display CSS-property set to none, then there might well be nothing to repaint, same if you did re-append the .blue element synchronously.

To put it in a bit less wordy way,

// js execution
DOM manip => mark layout as dirty
DOM manip => mark layout as dirty
... there may be a lot here

// Before screen refresh
if(layout.isDirty()) 
  layout.recalc() // will itself mark repaint as dirty if needed
if(renderer.isDirty())
  rendered.repaint()



回答2:


Yes because that's the only way you can remove an element, ...via it's parent, i.e., .removeChild(). The DOM then may or may not undergo what's called a Reflow depending on what changes result.



来源:https://stackoverflow.com/questions/50789614/what-exactly-updates-when-the-dom-is-manipulated

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!