preface
There is no doubt that React and Vue are the two most popular front-end frameworks. However, these two frameworks without exception give up the use of traditional DOM technology, but use jS-BASED Virtual DOM technology, also known as Virtual DOM. So, what exactly is the Virtual DOM? Why do the two most popular frameworks all use Virtual DOM? Let me, the front-end guy, take a good look at the DOM DIFF algorithm.
What is the Virtual DOM?
As literally said, Virtual DOM is the Virtual DOM, which is characterized by the use of Javascript to simulate the DOM structure, and compare the changes of DOM in the JS layer. Specific operations are as follows:
<ul class="list"> <li class="item">wjy</li> <li class="item"> <li > <li class="item"> Props: {class: 'list'}, children: [{tag: 'li', props: {class: 'item'}, children: [' Jackson]}]}Copy the code
Some friends may be a little confused, ordinary HTML DOM structure is not good? It’s easier to understand and the code is simpler, so why use nested recursive virtual DOM forms? In fact, this has to do with the fact that the normal DOM is very performance consuming in the process of re-rendering. The DOM operation looks simple, but in fact it is quite inefficient. This is because if it is in the real DOM that needs frequent modification, the Virtual DOM with JS structure which looks more complex will be more efficient.
The reason for using the Virtual DOM
DOM rendering page operation flow
-
When the browser gets the corresponding HTML file from the server through the domain name, the browser will first build DOM tree and CSSOM tree. About the concept of tree, students who have learned data structure and algorithm may be impressed by the node concept of tree.
-
In the HTML DOM, everything is a node, and the DOM is HTML treated as a tree of nodes, with hierarchical relationships between nodes. DOM node trees correspond to tags in HTML to form a DOM tree
-
The HTML file
- The HTML DOM tree
The same. In A CSS document, all elements are nodes that correspond to tags in HTML, forming a CSSOM tree as shown in the figure below
Warning! If JS related content is encountered during DOM tree construction, DOM tree construction will stop immediately. This is because JS can operate on DOM nodes. In order to prevent JS from affecting the COMPLETED DOM, browsers will prevent DOM tree construction to save resources.
inDOM
Trees andCSSOM
In the process of tree construction, the rendering tree is also gradually formed. The browser will carry out webpage layout and drawing process according to the constructed rendering tree, and continue to build the webpage. The specific operation flow chart is as follows:
In general, the normal operation of a page rendering is to manipulate the DOM, modify and reset the innerHTML to render the page, and for each DOM update, the rendering process is redrawn and rearranged.
Advantages of Virtual DOM
However, for large page projects or web pages with multiple tags and attributes, conventional DOM operations are too time-consuming. Each simple modification requires the redrawing and rearrangement of a large number of DOM nodes, which greatly reduces the page rendering efficiency. As a result, when the front-end developers face DOM bottlenecks,Virtual DOM shows great superiority as a lightweight JavaScript object, and smoothly gets the favor of front-end developers.
When the page is re-rendered,Virtual DOM performs DOM diff calculation twice and finds the difference. It only needs to modify different parts of the DOM tree. It can also be understood that Virtual DOM makes a middleware. JS is used to modify the Virtual DOM first, and all changes are added to the real DOM of the page after the differences are compared. Therefore, the biggest advantage of Virtual DOM is that it is completely different from the native DOM, and DOM reconstruction and creation are required after comparison, because this is very performance consuming and expensive for the operation of large projects. Therefore, no matter what size of web pages, Virtual DOM is undoubtedly a very efficient and excellent choice to abandon the traditional DOM.
How to represent the DOM in virtual DOM
First, create a new dom diff project in vscode, initialize the project, and install the corresponding components
Since it is a DOM tree, when converting HTML to a DOM tree, you use a recursive form, first creating nodes, then setting up attributes, and then setting up child nodes
<ul class="list"> <li class="item">wjy</li> <li class="item"> let virtualDOM = createElement('ul', { class:'list', }, [ createElement('li',{ class:'item' },['wjy']), CreateElement ('li',{class:'item'}),])Copy the code
Then, create a new element.js file to export to finish the page rendering
Class Element {constructor(type,props,children){this.type = type; this.props = props; this.children =children; } } // const createElement = (type,props,children) => { return new Element(type,props,children); Const render = (domObj) => {let el = document.createElement(domobj.type); for(let key in domObj.props){ setAttr(el,key,domObj.props[key]); } domObj.children.forEach(child => { child = (child instanceof Element) ? render(child) : document.createTextNode(child); el.appendChild(child); }) return el; } function setAttr(node,key,value){ switch(key){ case 'value': if(node.tagName.toLowerCase() === 'input' || node.tagName.toLowerCase() ==='textarea' ){ node.value = value; }else{ node.setAttribute(key,value) } break; case 'style': // node.setAttribute('style',value) node.style.cssText = value; break; default: node.setAttribute(key,value) break; Const renderDOM = (el,target) => {target.appendChild(el); } export {createElement, render, renderDOM}Copy the code
Get the real DOM on the console
Page rendering successful! 😃
DOM DIFF algorithm
Operational changes in user interaction page after operation, the virtual DOM node in the tree change, real nodes at this time, however, has not changed, in order to make changes and real page synchronization, we will use the DOM DIFF algorithm to find out the differences of the two tree, then generates difference patch object, to apply different patch object to true DOM node, The page is rendered and updated.
The time complexity of the traditional Diff algorithm reaches O(n^3). In order to meet the purpose of refreshing the whole page every time, the exponential growth of the performance cost cannot meet the performance requirements. Therefore, The engineers of Facebook optimized this algorithm and reduced the complexity of the Diff algorithm to O(n) through the formulation of the Diff strategy.
The Diff strategy
DOM
Node operations across hierarchies are so rare that they can be ignored- Two components with the same class will produce similar tree structures, and two components with different classes will produce different tree structures
- A group of children of the same level that they can pass through
uuid
To distinguish between
The Diff granularity
Due to the different granularity of DIFF, the DIFF algorithm is executed in the following order
- Tree DIFF
- Component DIFF
- Element DIFF
patch
According to the DIff strategy and the comparison algorithm in React DIFF, the two virtual DOM are compared through depth-first traversal. If there is any difference, the operation corresponding to the index value of the node traversed is stored, which is also called patches.
Then we go through the depth-first traversal of the real DOM again, the index in the patch object will correspond to the DOM, and we have completed the DOM update operation.
conclusion
In the Internet environment, refreshing interactive pages at any time is a routine operation for us to surf the Internet, but this simple operation is the result of algorithm optimization for many times. The underlying principle of DOM DIFF is very complex, if you are interested in the friends, you can search the relevant literature, because this article is only a brief analysis, so too many aspects will not be described, if there are knowledge mistakes in this article, also welcome to correct! Accept all reasonable criticism with an open mind! 😉
If this article is helpful to your understanding of DOM Diff algorithm, I also hope you can give me a thumbs up 😃. The main answer is the front end of the beginner. Every thumbs up is my motivation to move forward, AND I will continue to update the Nuggets blog 🤗
Thank you ~
Refer to the reading
Blog.csdn.net/one_girl/ar…
www.cnblogs.com/wubaiqing/p…
www.cnblogs.com/dashnowords…