This content is the courseware of "Javascript Video for Web Front-end Development", please cooperate with the "Javascript" video course of Master Brother.
The DOM specification does not include all the events supported by all browsers, and many browsers implement some custom events that are later supported by HTML5;
Contextmenu event:
Win95 introduced the concept of context menus in PC applications, that is, menus that are called up when the mouse right-clicks or when the menu key on the keyboard is pressed, and later, this concept is introduced into the Web domain; in order to implement context menus, it is necessary to determine when the context menu should be displayed and how to block the default context menu associated with the operation; in order to solve this problem, the event of contextmenu appeared. so that the developer can cancel the default context menu and provide a customized menu;
The contextmenu event belongs to the mouse event type, so its event object contains all the properties related to the position of the mouse; to indicate that it is a mouse event type and is right-clicked, it has a button value of 2 and a value of which is 3; and its target is the element where the user action occurred
The event is bubbling, so you can specify an event handler for the document to handle all such events in the page;
Custommenu events are typically used to display a custom context menu, while onclick event handlers are used to hide the menu;
beforeunload pre-uninstall event:
When the browser window is closed or refreshed, the event is triggered, the event should be registered on the window object, when this event is triggered, the current page will not close directly, it can be used to cancel the uninstall and continue to use the original page, the purpose is to make it possible for the developer to block this operation before the page is unloaded, but can not cancel the event completely, the intention is to give control to the user, which will display a message to inform the user that the current page is going to be uninstalled, asking if the user really wants to close the page, At the discretion of the user;
The event does not bubble;
The window.alert(), window.confirm() and window.prompt() methods cannot be called in this event, because for the forbeforeunload and unload events, it is required that the event handler cannot block the current thread inside, and these methods will block the current thread, so the H5 specification clearly stipulates that the invocation of these methods is directly ignored in the foreunload and unload;
In order to display a dialog box that asks if the user really wants to leave the page, according to the specification, the preventDefault() method should be called in the event handler, but not all browsers follow this specification, such as:
IE displays a default dialog box (are you sure you want to leave this page?). Leave this side/stay on this page), but other browsing does not respond;
If you want to implement a custom hint, you can have the event handler return a string, or set the value of event.returnValue to the characters to display, such as:
IE displays a dialog box and includes the returned string, but other browsers do not support it, other browsers must return it as the value of the function, such as:
Example: Autosave data:
beforeunload is triggered before the unload event;
There are often some application scenarios that perform some business before the user leaves the page, which uses the onbeforeunload event; for example, the business of recording the user's stay time includes this in the application of GA and other page visit statistics:
DOMContentLoaded event:
The windowload event will fire when everything in the page has loaded, but the process may wait too long because there are too many external resources to load; the DOMContentLoaded event will fire after forming a complete DOM tree, without waiting for images, JS files, CSS files or other resources to be downloaded;
With this event, you can add event handlers for documentation or window;
The event object is of the Event type, which does not provide any additional information, and can also be registered on the window object, whose target is a document;
The event is always triggered before the load event, so the purpose of the event is to support the addition of event handlers early in the page download, so that the user can interact with the page as early as possible;
IE8 and the following browsers do not support this event, you can set a timeout call of 0 milliseconds during page load: during the page download and refactoring period, there is only one js processing process, so the timeout call will be triggered immediately at the end of the process; whether this time can be synchronized with the time of DOMContentLoaded depends mainly on the browser and other code in the page; in order to ensure that it is valid, it must be called as the first timeout in the page; even so, There is also no guarantee that the load event will be triggered earlier in all environments, such as:
There are also two scenarios:
One is to create an empty script tag, the attribute has defer, and then fire DOMContentLoaded when the onreadystatechange is completelete;
One is to judge DOMContentLoaded by calling doScroll('left'), the basic idea of which is to detect document.documentElement.doScroll("left"),because calling doScroll before the DOM tree is created will throw an error, and if it doesn't throw an error, it means that the DOM is ready;
Another option:
or:
Readystatechange readiness state change event:
IE provides the readystatechange event for some parts of the DOM document, the purpose of which is to provide information about the load state of the document or element; the event is triggered when the readyState property of an object changes;
Each object that supports the event has a readyState property that may contain one of the following 5 values;
uninitialized: the object exists but has not been initialized;
loading: the object is loading data;
loaded: The object loads data to complete
interactive: the object can be manipulated, but it has not been fully loaded;
complete: the object has been loaded;
Not all objects go through several phases of the event, i.e. if a stage does not apply to an object, it is entirely possible for that object to skip that phase;
For documentation, there will be three stages of loading, interactive and package, such as:
The readystatechange event that fires when the readyState status is "interactive" is roughly the same time as the DOMContentLoaded event;
Simulate the DOMContentLoaded event:
When the readyState value is completelete, it is also about the same time as the load event, but always before the load event;
Simulate load events such as:
Between interactive and completelete, you can do something about the DOM, or do some preparation operations to speed up the loading of the page, such as:
However, the interactive interaction phase may occur earlier or later than the complete stage, and the order cannot be guaranteed, so in order to be as early as possible, it is necessary to detect both the interaction and completion phases;
While DOMContentLoaded events can be simulated very closely using readystatechange, they are fundamentally different;
Load event and readystatechange event, in rare cases, it is impossible to predict the order in which the two events are triggered, if there are a large number of resources in the page, readystatechange may be triggered after the onload event;
Example: Use load, readystatechange, and DOMContentLoaded events to determine whether the DOM is ready, and if so, you can execute the callback function;
Below IE10, <script> and <link > elements also fire readystatechange events, which can be used to determine whether external JS and CSS files have been loaded; but are not supported by other browsers;
In addition, the readystatechange event also exists in other APIs, such as XMLHttpRequest;
Example: Wrapping the whenReady() function to listen for DOMContentLoaded and readystatechange events, such as:
hashchange event:
is an event new to HTML5 to notify developers when the parameter list of a URL (i.e. all strings after the "#" sign in the URL) changes; this event is added because in Ajax applications, developers often use the URL parameter list to save state or navigation information;
The hashchange event handler must be added to the window object, and then the URL parameter list will be called whenever it changes;
HashChangeEvent class:
Represents a change event that fires when the fragment identifier in the URL changes; the fragment identifier refers to the # sign in the URL and the part after it; it inherits from the Event class;
The HashChangeEvent object contains two additional attributes: oldURL and newURL, which hold the complete URL before and after the parameter list changes (that is, the oldURL saves the URL before the jump, and the newURL saves the new URL that is about to be jumped), such as:
Except for IE7 and below, which does not support hashchange events, all browsers do;
Although IE7 versions and later support hashchange events, the HashChangeEvent class is treated as a normal Event, so these two properties of the HashChangeEvent object are not supported, but the locale object can be used to determine the current parameter list, such as:
Detect if the browser supports hashchange events, such as:
If IE8 is running in IE7 document mode or the following browsers of IE7, even if the function is invalid, it will still return true, and a more secure detection method can be taken:
example:
HTML5 also boasts a large number of other events, such as multimedia events about audio and video, drag-and-drop events, history management events, etc.;
There are also device events (i.e., mobile devices), including touch and gesture events;
Memory and Performance:
In JS, the number of event handlers added to the page will be directly related to the overall performance of the page; for example, each function is an object and will occupy memory; the more objects in memory, the worse the performance; the number of DOM visits caused by all event handlers must be specified in advance, which will delay the interaction readiness time of the entire page;
Event delegate:
Event delegates take advantage of event bubbling to specify only one event handler to manage all events of a certain type; for example:
With event delegates, you only need to add an event handler at the highest possible level in the DOM tree, such as:
If feasible, consider adding an event handler to the document object to handle a specific type of event that occurs on the page, so that the advantages of Shan are:
The document object is quickly accessible: an event handler can be added to it at any point in the page's life cycle (without having to wait for DOMContentLoaded or load events);
It takes less time to set up an event handler in a page, less DOM references to just one event handler, and less time;
The entire page takes up less content space, which can improve overall performance;
The most suitable events for using event delegation techniques include: click, mousedown, mouseup, keydown, keyup, and keypress; although the mouseover and mouseout events also bubble up, it is not easy to handle them properly, and it is often necessary to calculate the position of elements;
To remove an event handler:
Whenever an event handler is assigned to an element, a connection is established between the running browser code and the JS code that supports page interaction; the more such connections, the slower the page executes; event delegation techniques can be used to limit the number of connections; and the event handler can be removed at unneeded times;
Memory is left with outdated and unused "dangling event handlers", which is also the main cause of web application memory and performance problems;
In two cases, this can cause the above problems; the first is when removing an element with an event handler from a document, this may be done through pure DOM operations, such as using the moveChid() and reverseChild() methods, or replacing a part of the page with innerHTML, the event handler originally added to the element may not be garbage collected;
Remove the button's event handler before setting the div's innerHTML property;
There is also a scenario, that is, to use the method of event delegation, for example, if you know in advance that it is possible to replace part of the page in the future with innerHTML, etc., then do not register the event handler directly with the elements in this part, but register with the higher-level elements that will not be replaced;
Note that deleting the target element in the event handler also prevents event bubbling, which is a prerequisite for event bubbling in the document;
When unloading pages, if the event handlers are not cleaned up, they will remain in memory; each time the page is loaded and then unloaded, the number of objects stuck in memory will increase, especially IE;
Therefore, before unloading the page, all event handlers are removed through the onunload event handler; onunload is similar to the "undo" operation, as long as the things added through the onload event handler are finally removed through the onunload event handler;