Summary of DOM Event Optimization in Javascript

Source: Internet
Author: User

This article provides some suggestions on how to optimize DOM events in Javascript. Although many people now use the jquery plug-in, dom events are very important, I will share my experience on optimization.

In the development of JavaScript programs, DOM events that are frequently triggered, such as mousemove and resize, and mouse wheel events that are not so commonly used: mousewheel (in Firefox, scroll wheel event is DOMMouseScroll ).

In order to ensure timely response to these events, the browser triggers the event more frequently. The actual trigger frequency varies with browsers, but the difference is not large. Most of the time, when using these events in scenarios that require performance attention, various methods will be used to optimize the trigger frequency of the events. The following describes some of my optimization methods.

Optimization of mousemove in dragging
Drag (Drag) is a common function. Before the browser implements native Drag, the Drag effect can be simulated through three event types: mousedown, mousemove, and mouseup, of course, we will not talk about how to implement a drag-and-drop function.

In a drag-and-drop application, the mousemove event must ensure the smoothness of the drag-and-drop operation and the performance of the drag-and-drop operation. How can we maintain a balance between the two?

You can set a counter to remove half of the mousemove event triggers. The Code is as follows:

The Code is as follows: Copy code

Var count = 0;

Elem. onmousemove = function (){
Count ++;

// Do not execute mousemove when the counter is an even number.
If (count % 2 = 0 ){
Return;
}

// Code for implementing the drag and drop function...
};

The above only adds a few lines of code. By judging whether the counter is an even number, you can remove half of the number of mousemove event executions, while the smoothness of the drag-and-drop function is basically not affected.

Mousemove: Simulate the mouseenter Effect
Recently, we have encountered such a requirement that we need to bind an event to the image. When we move the mouse over the image, we need to enlarge the image. The first reaction of most people is to directly use the mouseenter event to process it. However, the use of the mouseenter event will trigger by mistake. Even if you can use a timer, it will trigger by mistake, because the image triggers a large area for the mouseenter event, when you move the mouse over a 200*200 image, you can set a 500-millisecond latency for mouseenter, which may not be as expected. The interaction mode is further optimized. When you move the mouse over an image quickly, no event is triggered. The event is triggered only when the mouse stays on the image for a short time. You can add a timer to mousemove to achieve this effect. The Code is as follows:

The Code is as follows: Copy code

Var timer,
Move = function (){
ClearTimeout (timer );
// Set a shorter Timer
Timer = setTimeout (function (){
// Here is the code to enlarge the image...
},200 );
};

Img. onmousemove = move;
Img. onmouseout = function (){
ClearTimeout (timer );
};

The mousemove event triggered by frequent mouse movement will clear the last added timer. The event will be triggered only when the mouse stay time exceeds the set 200 milliseconds, of course, remember to clear the timer when you move the mouse away. 360 image search uses this trigger method, so that it will not be triggered incorrectly.

Resize event Optimization
Resize is an event triggered when the browser window size is changed. A change usually triggers 2 or 3 resize events, which is easier to trigger for IE6/7 resize. The resize event is usually used when the window size changes, and the webpage layout is also adjusted according to the window size. If the Adaptive Layout consumes a lot of performance, pay special attention to the frequency of resize triggering. The timer is also used for implementation.

The Code is as follows: Copy code

Var throttle = function (fn, timeout ){
Var timer;

Return function (){
Var self = this,
Args = arguments;

ClearTimeout (timer );

Timer = setTimeout (function (){
Fn. apply (self, args );
}, Timeout );
};
};

Window. onresize = throttle (function (){
// Code for Adaptive Layout...
},100 );

Through repeated debugging, it is found that the effect of adding a 100 millisecond delay to resize is ideal, which not only ensures the timeliness of the event, but also achieves the goal of optimization.

Optimization of mousewheel events
Mousewheel is an event triggered when the scroll wheel is clicked. In Firefox, the event name is DOMMouseScroll. In some cases, for example, you can use the scroll wheel to control the frontend and backend switching of the lightbox component image, or zoom in or out the map with the scroll wheel of the mouse. The scroll wheel is usually flexible and may scroll several times at a time. However, in specific applications, such a flexible Scroll will inevitably trigger incorrectly in the scenario mentioned above. The preceding encapsulated throttle function can be used to slightly change the time interval to achieve the same optimization effect.

The Code is as follows: Copy code

Window. onmousewheel = throttle (function (){
// Operation code for scroll wheel...
},200 );

When the scroll wheel is set to a latency of 200 milliseconds, the result is satisfactory.

Most of the above optimization methods are implemented through the timer. The key is how to use them flexibly. These optimizations are not limited to performance optimization, but also the optimization of interaction effects. In the end, they are from the perspective of the previous end, starting from the details to improve the user experience.

Javascript performance optimization considerations. Record it.


1. Add Dom in batches

Try to use the innerHTML modification method instead of the appendChild method. Because innerHTML has a lower overhead, faster speed, and more memory security.

One thing to note is that when you use the innerHTML method to add, you must not use the innerHTML + = method in the loop, which will slow down the speed. Instead, you should use the array cache in the middle, call xx after the loop ends. innerHTML = array. join (''); or at least save to string and insert it into innerHTML.

This method is used to optimize the user list, and the loading speed is doubled.

2. Add a single Dom

This refers to the situation where a new node is loaded to a node with constantly changing content. For nodes with stable content, it is no problem to add any content. however, for nodes with dynamic content, try to use dom append to add subnodes to them.

This is because dom append does not affect other nodes. If the innerHTML attribute is modified, all child nodes of the parent node will be removed from the dom tree, then, the sub-node dom tree is re-painted based on the new innerHTML value. All events registered with the original sub-node will also become invalid.

To sum up, if the innerHTML + = code appears on a node with dynamic content, you should check whether there is a problem.

3. Create a Dom Node
Creating a dom node using createElement has an important detail: After executing the createElement code, append it to the dom tree; otherwise, if you assign attributes and innerHTML operations to the isolated node before it is loaded to the dom tree, the memory of the dom fragment cannot be recycled. this inconspicuous detail will cause a memory disaster once a large number of dom addition and deletion operations are encountered.

4. delete a Dom Node
Before deleting a dom node, you must delete the events registered on the node, whether registered in observe or attachEvent mode. Otherwise, memory cannot be recycled.

In addition, the latter should be selected between removeChild and innerHTML = '', because in sIEve (Memory Leak Monitoring Tool), the result of monitoring is that removeChild cannot effectively release dom nodes.

5. Create an event listener
The existing js library uses the observe method to create event listening, which isolates the circular reference between the dom object and the event processing function. Therefore, we should try to use this method to create event listening.

6. Listen to dynamic elements
Dom events are bubble up by default. The events that occur in the subnode can be handled by the parent node. the target/srcElement of the Event is still the deepest subnode that generates the Event. in this way, when the content is dynamically added and the child nodes need the same event processing function, you can refer to the event registration on the parent node, in this way, you do not need to register event listening for each subnode.

At the same time, this avoids memory that cannot be recycled. even if you use the Prototype observe method to register events and call stopObserving before deleting a node, a small amount of memory cannot be recycled. Therefore, you should register event listening for dom nodes as few as possible.

Therefore, when an event is registered in a loop in the code, it is time for us to consider the event escalation mechanism.

7. HTML Purification
HTML purification reflects the idea of taking responsibility for each other. HTML is only used for display and should not display attributes unrelated to display, such as onclick events, such as custom object attributes.

The preceding method can be used to avoid an event. An object attribute refers to a scenario in which the dynamically added content usually corresponds to an object, for example, in the user list of the chat room, each dom node that shows the user has a user object corresponding to it. In this way, only one id attribute corresponds to the user object in html, other information should be obtained through the user object.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.