A summary of the optimization of DOM events in JavaScript

Source: Internet
Author: User
Tags event listener

In the development of JavaScript programs, you often use a number of frequently triggered DOM events, such as MouseMove, resize, and not so commonly used mouse wheel events: MouseWheel (in Firefox, the wheel event is Dommousescroll )。

browser in order to ensure that these events can respond in a timely manner, the trigger frequency will be higher, the specific trigger frequency of the browser, although there are discrepancies, but not very much. Most of the time to use these events in the context of a performance-oriented scenario would be to optimize the trigger frequency of the event in a variety of ways, and here are some of my optimization methods.

Optimization of MouseMove in drag-and-drop
drag-and-drop (Drag) is a very common function, in the browser has not yet realized the original drag and drop, through the MouseDown, MouseMove, MouseUp 3 types of event can simulate the drag effect, of course, here does not talk about how to implement a drag-and-drop function.

MouseMove events in the drag-and-drop application to ensure that the flow of drag and drop, but also to ensure the performance of the drag, how to maintain the balance between the two?

You can set a counter to go off half of the MouseMove event trigger, the code is as follows

The code is as follows Copy Code

var count = 0;

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

Do not perform mousemove when the counter is even
if (count% 2 = 0) {
Return
}

Code to implement drag-and-drop functionality ...
};

The above only adds a few lines of code, by judging whether the counter is even, you can remove half the number of MouseMove event execution, while the flow of drag-and-drop function is basically unaffected.

The

MouseMove simulate MouseEnter effect
recently came across a need to tie an event to a picture and enlarge the picture when the mouse moves to the picture, most people's first reaction is to use directly MouseEnter event to handle. However, using the MouseEnter event will lead to a false trigger, although you can use the timer to match or will be triggered incorrectly, because the picture for the MouseEnter trigger area is relatively large, when the mouse across a picture of 200*200 size, at this time to MouseEnter set a 500 millisecond delay, the effect may not reach the expected. The interactive way to do further optimization, when the mouse quickly across the picture does not trigger events, only a short mouse pause in the picture before triggering events. This effect can be achieved by adding a timer to MouseMove. The code is as follows:

  code is as follows copy code

var timer,
    move = function () {
        cleartimeout (timer);
& nbsp;      //Set a shorter timer
        timer = settimeout (function () {
           //Here is the code to enlarge the picture ...
       }, 200);
   };
   
Img.onmousemove = move;
Img.onmouseout = function () {
    Cleartimeout (timer);
};

Frequent mouse movement triggered by the MouseMove event will erase the last timer added, only when the mouse stay longer than the setting of 200 milliseconds will trigger events, of course, when the mouse moved away must remember to clear off the timer. The 360 image search uses this triggering method, so that no more errors are triggered.

Optimization of resize events
Resize is the event that triggers when the browser window changes in size, which usually triggers 2, 3 resize events at a time, and is more likely to be triggered for IE6/7 resize. The Resize event is typically used when the window is resized, and the layout of the page is adapted to the size of the window. Adaptive layout If the performance of the consumption is greater, it is necessary to pay particular attention to the frequency of resize trigger. Also use the timer to implement.

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 Layouts ...
}, 100);

Through repeated debugging, it is found that the effect of adding a 100 millisecond delay to the resize will be more ideal, both to ensure the timeliness of the event, but also to achieve the goal of optimization.

Optimization of MouseWheel Events
MouseWheel is the event that triggers when the mouse wheel scrolls, in Firefox the event is named Dommousescroll, in some cases, such as by the mouse wheel to control the Lightbox component picture before and after switching, Or you can zoom in and out of the map by using the mouse wheel. The mouse wheel is usually more flexible and may scroll several times at a time, but in a specific application this too flexible scrolling is necessarily triggered incorrectly in the scenario mentioned earlier. The throttle function, which is encapsulated above directly, can be optimized by slightly changing the time interval.

The code is as follows Copy Code

Window.onmousewheel = throttle (function () {
Operation code when the wheel scrolls ...
}, 200);

The mouse wheel set a 200 millisecond delay will have a more desirable effect.

Some of the above optimization methods are mostly through the timer to achieve, the key is to see how flexible use. These optimizations are not limited to performance optimization, but also to the optimization of the interaction effect, in the final analysis, from the front end point of view, starting from the details to enhance the user experience.

JavaScript Performance tuning note some sections. Record it.


1. Add Dom in bulk

Try to use the way of modifying InnerHTML instead of appendchild; Because using InnerHTML is less expensive, faster, and more memory-safe.

One thing to note is that when added in InnerHTML mode, do not use InnerHTML + + in the loop to add, which will slow down the speed; Instead, it should be cached in the middle with an array, calling xx.innerhtml = Array.join (') after the loop ends; , or at least save it to a string and plug it into the InnerHTML.

The load speed is increased by one time after the user list is optimized in this way.

2. Single Add Dom

This refers to the situation where the new node is loaded into a constantly changing node, which is no problem for the content-stabilized node. However, for a node with dynamic content, it is possible to add child nodes to it using DOM append.

This is because the DOM append does not affect other nodes; If the InnerHTML property is modified, all child nodes of the parent node are stripped from the DOM tree, and the child node DOM tree is redrawn based on the new InnerHTML value; All events registered to the original child node will also be invalidated.

In summary, if there is a InnerHTML + + code on a node with dynamic content, you should consider whether there is a problem.

3. Create a Dom node
Creating a DOM node in createelement has a very important detail: After executing the createelement code, you should immediately append to the DOM tree; Otherwise, if the assignment of the orphaned node before it is loaded into the DOM tree, its properties and InnerHTML operations can cause problems that the DOM fragment memory cannot be reclaimed. This obscure detail, once encountered a large number of DOM additions and deletions operations, will cause memory disaster.

4. Delete a Dom node
Before deleting a DOM node, be sure to remove the event that is registered on that node, either in observe or attachevent, or it will result in memory that cannot be reclaimed.

Alternatively, between RemoveChild and Innerhtml= ', try to choose the latter. Because the result of monitoring in the sieve (Memory leak monitoring tool) is that the DOM node cannot be effectively freed with RemoveChild.

5. Create Event Monitoring
The existing JS library uses the observe method to create event monitoring, which isolates the circular references between the DOM object and the event handler function, so it should be used to create event monitoring as far as possible.

6. Monitor dynamic elements
Dom events are bubbling up by default, and events that occur in child nodes can be handled by the parent node. The target/srcelement of the event is still the deepest child node that generated the events. Thus, when the content is dynamically increased and the child nodes need the same event handler function, the event registration can be mentioned on the parent node, so that there is no need to register the event listener for each child node.

At the same time, this avoids the creation of memory that cannot be reclaimed. Even if you are registering events in Prototype observe and calling stopobserving before deleting a node, you will also generate a small amount of memory that cannot be reclaimed, so you should try to register event monitoring for DOM nodes as little as possible.

So, when the code appears in the loop to register the event, it is also time to consider the event to mention the mechanism.

7. HTML Purification
The refinement of HTML embodies a accountability idea. HTML is only used to display, try not to appear and display extraneous properties. such as the OnClick event, such as a custom object attribute.

Events can be avoided in the preceding ways, object properties refer to a scenario in which the dynamically added content is typically an object that corresponds to it, such as a list of users in a chat room, and each DOM node that displays a user has a user object that corresponds to it, so that in HTML, you should only Keep an id attribute and the user object, and the 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.