An example of this article is given to analyze the event delegation of JavaScript performance optimization. Share to everyone for your reference, specific as follows:
Bind a click event for each of the following Li
<ul id= "Mylinks" >
<li id= "Gosomewhere" >go somewhere</li> <li id=
"DoSomething" >Do something</li>
<li id= "Sayhi" >say hi</li>
</ul>
First, the traditional wording
var Item1=document.getelementbyid ("Gosomewhere");
var Item2=document.getelementbyid ("DoSomething");
var Item3=document.getelementbyid ("Sayhi");
Item1.onclick = function () {
console.log (' Gosomewhere ');
}
Item2.onclick = function () {
console.log (' dosomething ');
}
Item3.onclick = function () {
alert ("Hello");
}
In JavaScript, the number of event handlers added to the page is directly related to the overall performance of the page, and the more events, the worse the performance.
Causes are manifold:
1, each function is an object, will occupy memory, the more objects in memory, the worse performance.
2. The number of DOM accesses that must be specified in advance for all event handlers delays the interactive ready time of the entire page.
Ii. Commission of events
The solution to the "too many event handlers" problem is the event delegate.
Event delegates take advantage of event bubbling, which allows you to manage all events of a type by specifying only one event handler. For example, the Click event will always bubble to the document level. That is, we can specify an onclick event handler for the entire page without adding an event handler to each clickable element.
Event Delegate Method:
var List=document.getelementbyid ("Mylinks");
List.onclick = function (e) {
var target = e.target;
Switch (target.id) {case
"Gosomewhere":
console.log (' Gosomewhere ');
break;
Case "dosomething":
console.log (' dosomething ');
break;
Case "Sayhi":
alert ("Hello");
break;
}
}
The advantages of using event delegates:
1 The Document object will soon be accessible, and you can add event handlers for it at any point in the page life cycle (without waiting for domcontentloaded or load events). In other words, as long as clickable elements are rendered on the page, the appropriate functionality is immediately available.
2 It takes less time to set up an event handler on the page. Only a few DOM references are required to add one event handler, and less time is spent.
3 The entire page occupies less memory space, can improve the overall performance.
I hope this article will help you with JavaScript programming.