Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to understand the principle of Vue implementation and front-end performance optimization

2025-01-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article mainly introduces "how to understand Vue implementation principles and front-end performance optimization". In daily operation, I believe many people have doubts about how to understand Vue implementation principles and front-end performance optimization. Xiaobian consulted all kinds of materials and sorted out simple and easy-to-use operation methods. I hope it will be helpful for you to answer the doubts of "how to understand Vue implementation principles and front-end performance optimization". Next, please follow the editor to study!

First, the realization principle of Vue

1. Introduction to Vue

Now the big front-end era, is an era of turbulence and disputes, rivers and lakes have been divided into many schools, mainly led by Vue,React and Angular, forming a tripod situation of the front-end framework. The status of Vue in the front-end framework is like the jQuery in the past. Because of its easy to understand and high development efficiency, it has become one of the indispensable skills for front-end engineers.

Vue is a progressive JavaScript framework, which perfectly combines third-party plug-ins and UI component libraries. The biggest difference between Vue and jQuery is that Vue does not need developers to directly operate the DOM node to change the page rendering content. On the basis of application developers with certain HTML, CSS and JavaScript, they can quickly get started and develop elegant and concise application modules.

But when we mention Vue, we focus more on its usage than on how it solves front-end problems, which is more or less sub-healthy. People with front-end development experience must have encountered strange problems in the development process, and then confused to solve them, if they encounter similar problems again, they will be at a loss again, as a front-end engineer, whether we can accurately locate the cause of the problem and solve it in time depends on whether we have a deep understanding of the front-end framework.

2. The principle of Vue.

2.1 Virtual DOM (Virtual DOM)

With the development of the times, the page interaction effect of Web application is more and more complex, the page function is more and more abundant, the state that needs to be maintained is more and more, and the DOM operation is more and more frequent. Although the operation of DOM is simple and easy to use, it can cause problems of difficult maintenance.

During the execution of the program, each node and state will be associated and mapped one by one when Watcher is initialized. When setter listens to changes in the state of Data, it will notify Watcher,Watcher of these changes to the DOM that has been recorded and the nodes related to these states, thus triggering the rendering process of the page. After receiving the state change, the component converts the template into the rendering function Render through compilation, and executes the rendering function to get a virtual DOM tree. By comparing the old virtual DOM with the newly generated virtual DOM tree, the corresponding actual DOM node is updated and the page rendering is performed.

Almost all mainstream front-end frameworks use virtual DOM, but when using virtual DOM, neither Angular nor React can determine which state has changed, so it is necessary to make a violent comparison between the old virtual DOM and the new virtual DOM, but Vue has updated the view through fine-grained binding since version 1.0. When the state changes, Vue can know which state and which nodes need to change, so as to update this node. However, this fine-grained change detection will have some memory overhead that affects performance. The more complex a project, the greater the overhead.

After Vue version 2.0, in order to optimize performance, virtual DOM is introduced and a compromise is chosen, which does not require violent comparison of the whole new and old virtual DOM, nor does it need to update the view through fine-grained binding, that is, Watcher snooping is carried out on a component-by-component basis, that is, even if multiple nodes in a component use a state, only one Watcher is needed to listen for the change of the state. When this state changes, Watcher informs the component that the nodes are compared and re-rendered through virtual DOM.

2.2 implementation principle of commonly used instructions

Instruction refers to the "v -" prefix provided by Vue. When the content of the expression in the instruction changes, it will affect the content of DOM. Vue.directive global API can create custom instructions and get global instructions. In addition to custom instructions, Vue also has some instructions commonly used in the development process, such as v-if, v-for and so on. When the Vue template is parsed, the instruction is parsed to AST, and the instruction function is implemented in the process of generating a string using AST.

When parsing the template, the instructions on the node are parsed and added to the directives attribute of AST. Directives sends the data to VNode. When the virtual DOM renders the page, some hook functions are triggered. When the hook function is triggered, the instruction has taken effect.

2.2.1 principle of v-if instruction

Use the v-if directive in your application:

Create if create else

Generate during the compilation phase:

(create)? _ c ('div', [_ v ("create if")]): _ c (' div', [_ v ("create else")])

When the code executes, which node is selected based on the value of create.

2.2.2 principle of v-for instruction

Use the v-for directive in your application:

{{item}}

Generate during the compilation phase:

_ l ((list), function (item, index) {return _ c ('li', [_ v (_ s (item)])}))

_ l is an alias for renderList. When the code is executed, the _ l function loops the list variable, calls the function passed in the second parameter, and passes two parameters: item and index. When the _ c function is called, the _ v function is executed to create a node.

2.2.3 principles of custom instructions

In the application, the processing logic of the instruction listens to the create function, the update function and the destory function, respectively. The specific implementation is as follows:

Export default {create: updateDirectives, update: updateDirectives, destory: function unbindDirectives (vnode) {updateDirectives (vnode, emptyNode)}}

When the hook function is triggered, the updateDirectives function is executed as follows:

Function updateDirectives (oldVnode, vnode) {if (oldVnode.data.directives | | vnode.data.directives) {_ update (oldVnode, vnode)}}

In this function, regardless of whether there is an old virtual node or not, the _ update function is executed as long as there is a directives in it. The code for the _ update function is as follows:

Function _ update (oldVnode, vnode) {const isCreate = oldVnode = = emptyNode const isDestory = vnode = = emptyNode const oldDirs = normalizeDirectives (oldVnode.data.directives, oldVnode.context) const newDirs = normalizeDirectives (vnode.data.directives, vnode.context) const dirsWithInsert = [] const dirsWithPostpatch = [] let key, oldDir, dir for (key in newDirs) {oldDir = oldDirs [key] dir = newDirs [key] if (! oldDir) {/ / New instruction triggers bind callHook (dir, 'bind', vnode) OldVnode) if (dir.def & & dir.def.inserted) {dirsWithInsert.push (dir)} else {/ / instruction already exists triggering update dir.oldValue = oldDir.value callHook (dir, 'update', vnode) OldVnode) if (dir.def & & dir.def.componentUpdated) {dirsWithPostpatch.push (dir)}} if (dirsWithInsert.length) {const callInsert = () = > {for (let I = 0) I

< dirsWithInsert.length; i++) { callHook(dirsWithInsert[i], 'inserted', vnode, oldVnode) } } if (isCreate) { mergeVNodeHook(vnode, 'insert', callInsert) } else { callInsert() } } if (dirsWithPostpatch.length) { mergeVNodeHook(vnode, 'postpatch', () =>

{for (let I = 0; I < dirsWithPostpatch.length; iTunes +) {callHook (dirsWithPostpatch [I], 'componentUpdated', vnode, oldVnode)})} if (! isCreate) {for (key in oldDirs) {if (! newDirs [key]) {callHook (oldDirs [key],' unbind', oldVnode, oldVnode, isDestory)}

IsCreate: determines whether the virtual node is a newly created node.

IsDistory: determines whether to delete an old virtual node.

OldDirs: an old set of instructions, instructions saved in oldVnode.

NewDirs: a new set of instructions, instructions saved in vnode.

DirsWithInsert: the list of instructions that trigger the inserted instruction hook function.

DirsWithPostpatch: the list of instructions that trigger the componentUpdated hook function.

The result of fetching the instructions used in the template from the custom instruction set registered by the user through the normalizeDirectives function is as follows:

{v-customize: {def: {inserted: F}, modifiers: {}, name: "customize", rawName: "v-customize"}}

The code for the custom instruction is:

Vue.directives ('customize', {inserted: function (el) {el.customize ()}})

When comparing and rendering a virtual DOM, different hook functions are triggered according to different scenarios. When a new actual node is created using a virtual node, the create hook function is triggered, and when a DOM node is inserted into the parent node, the insert hook function is triggered.

The callHook function executes the hook function in the following way:

Function callHook (dir, hook, vnode, oldVnode, isDestory) {const fn = dir.def & & dir.def [hook] if (fn) {try {fn (vnode.elm, dir, vnode, oldVnode, isDestory)} catch (e) {handleError (e, vnode.context, `directive ${dir.name} ${hook} hook`)}

The parameter meanings of the callHook function are:

Dir: instruction object.

Hook: the name of the hook function to be triggered.

Vnode: a new virtual node.

OldVnode: the old virtual node.

IsDestory: determines whether to delete an old virtual node.

All the hook functions that the virtual DOM triggers when rendering and their triggering mechanisms are as follows:

It is important to note that the remove function is triggered only if an element is removed from its parent element, and the remove function is not triggered if the element is a child of the removed element.

Second, front-end performance optimization

In an application, the front end mainly undertakes the function of sending a request to the server when the user opens a page, receiving the page returned by the server for rendering and presenting the rendering results to the user.

To improve the front-end performance, we need to start from the client-side and server-side interaction and browser parsing pages independent of user operations, that is, from the two aspects of transmission and rendering.

1. Request transmission

1.1 request Dimension

Based on the HTTP 1.1 protocol, which is widely used in front-end and back-end transmission, optimization can be made from two aspects: compressing the size of requests and reducing the number of requests. The main optimization methods are as follows:

1.2 Protocol Dimension

From 1. 0 short connection to 1. 1 long connection to HTTP2.0, 3. 0, many changes have been made, and each protocol upgrade is a leap for front-end performance optimization. New features of HTTP2.0 are as follows:

Binary framing: HTTP2.0 adds a binary framing layer between the application layer and the transport layer, divides all transmitted information into smaller messages and frames, and encodes them in binary format, so that the communication can be completed on an TCP connection that can carry any number of two-way data streams.

Compression header: using the HPACK algorithm, it is stipulated that the "header table" will be used and maintained on the client side and server side to track and store the key-value pairs sent before. For the same header, it is no longer necessary to send through the request, which reduces the header overhead.

Multiplexing: the client and server can decompose HTTP messages into independent frames, send them out of order, and finally reassemble them at the other end.

Request priority: each stream can have a priority value of 31bit: 0 to the highest priority, and 2 to the power of 31 to the lowest priority.

Server push: by providing push-promise frames to achieve the real sense of browser push, get rid of the pseudo-real-time scenario of using ajax polling.

2. Browser rendering

2.1 browser single-thread parsing rendering blocking

The main components of the browser are as follows:

Its resident threads are as follows:

Due to the mutual exclusion between the Gui thread and the JS engine thread, a series of optimization methods have been derived to avoid blocking in the rendering process, such as putting the style file in the header and the script file at the end of the DOM node; loading scripts that do not need to operate DOM by dynamically creating script tags; adding async or defer to the script file.

2.2 huge DOM overhead

In the process of browser rendering, the huge DOM overhead has undoubtedly become the biggest bottleneck in rendering efficiency. You can output an empty DOM node with the following code to view the more than 300 attributes and events it contains.

Let ele = document.createElement ("div") let obj = {} for (const prop in ele) {obj [prop] = Ee [prop]} console.log (obj)

2.2.1 redrawing and reflux

Redrawing refers to when the page shows some elements in the element need to update attributes, these attributes only affect the appearance and style of the element, but not the layout, such as background-color. Backflow is when some (or all) of the page display elements need to be rebuilt due to changes in the size, layout, hiding, and so on. Obviously, redrawing does not necessarily lead to reflow, which will inevitably lead to repainting.

They all bring some DOM overhead, which need to be avoided. Common ways to avoid them are to avoid triggering synchronous layout events; for complex animation effects, use absolute positioning to keep them out of the document stream; css3 hardware acceleration (transform, opacity, filters, Will-change), and so on.

2.2.2 Virtual DOM

In view of the huge DOM overhead, in addition to trying to avoid redrawing and reflow, there is also a popular virtual DOM method used by major frameworks such as VUE and react in recent years.

Virtual DOM is a tree based on js objects, which uses object attributes to describe nodes and is an abstraction of DOM, which is mapped to the real environment through a series of operations.

Use a piece of code to simulate this process. First, the user writes the template as follows:

{{item}}

The compiled content is shown below, creating nodes in the form of creatElement syntax sugar.

CreateElement {"ul", {attr: {id: "myId"}, [createElement ("li", 1), createElement ("li", 2), createElement ("li", 3)]}

After the execution of the rendering function, the virtual DOM tree is generated, and its approximate structure is as follows:

Finally, the virtual DOM tree is transformed into real DOM.

The optimization of the DOM overhead of virtual DOM performance is mainly reflected in that when the node changes, it can compare the changes of the virtual DOM structure before and after the change through the differ algorithm, and make necessary adjustments through the modification of node attributes, rather than mindless destruction of old nodes to create new nodes.

The main steps of this process are: represent the structure of the DOM tree with the js object structure, and then use the tree to construct a real DOM tree and insert it into the document; when the state changes, reconstruct a new tree, compare it with the old tree, and record the differences; apply the recorded differences to the real DOM tree built. It should be noted that the differ algorithm follows the principle of peer comparison, and the cross-level DOM adjustment should be minimized in the process of use.

At this point, the study on "how to understand the principle of Vue implementation and front-end performance optimization" is over. I hope to be able to solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report