This is the 27th day of my participation in the August More Text Challenge

Virtual dom

Frequent and complex DOM operations are often the source of front-end performance bottlenecks, and Vue provides a virtual DOM solution

The core idea of the virtual DOM is to provide a convenient tool for minimizing DOM manipulation of complex document DOM structures. This statement, perhaps too abstract, Outlines the design philosophy of the virtual DOM

(1) provide a convenient tool to ensure development efficiency (2) ensure minimal DOM operations, so as to ensure execution efficiency

That is, the framework/tools for the virtual DOM all do this:

  1. Originally render the real DOM from the virtual DOM tree
  2. When the data changes, or the page needs to be re-rendered, a new complete virtual DOM is generated
  3. Compare the new virtual DOM to the old one (using the diff algorithm). Once you have what needs to be updated, update the content

In this way, you can drastically reduce the number of real DOM operations and improve performance

What is the virtual DOM? Relation to key? Virual DOM records a copy of A DOM node with JS objects. When DOM changes, the virtual DOM is first diff to calculate the minimum difference, and then the real DOM is modified.

When manipulating the DOM in the traditional way, the browser runs the process from beginning to end, starting with building the DOM tree, which is inefficient. The virtual DOM is represented by javascript objects, and manipulating javascript is easy and efficient. The virtual DOM has a layer of mapping relationship with the real DOM. Many places that need to manipulate the DOM will operate the virtual DOM and finally update the DOM. Thus, performance can be improvedCopy the code

Diff algorithm of virtual DOM

In the virtual DOM, when the state of the DOM changes, the virtual DOM performs Diff operations to update only the DOM that needs to be replaced, rather than redrawing the entire DOM. In the Diff algorithm, only the nodes of the two DOM trees before and after are compared at a flat level, without depth traversal.

1. If the node type changes, uninstall the old node and replace it with the new node. The old node including the following child nodes will be uninstalled. 2. The node will not be uninstalled and the node will be updated if the node type and attribute or value remain unchanged. 3. Text change, directly modify the text content. 4. When moving, adding, or deleting child nodes:

If you want to insert node F in the middle, the simple and crude way is: unload C, load F, unload D, load C, unload E, load D, load E. The diagram below:

When writing code that does not define a key for an array or enumeration type, the above rough algorithm is used. If a key is added to an element, Vue can directly find the specific location to operate according to the key, which is relatively efficient. The diagram below: