Understand Load Events in js

  • 2021-07-16 01:51:16
  • OfStack

Previous words

When you mention loading events, you might think of window. onload, but in fact, loading events are a big class of events, which will be described in detail in this article

load

The load event is one of the most commonly used events. When the page is fully loaded (including all images, javascript files, CSS files and other external resources), the load event on window will be triggered

[Note] IE8-The browser does not set the srcElement property for this event, while the target property of other browsers points to document


window.onload = function(e){
 e = e || event;
 var target = e.target || e.srcElement;
 //IE8- Browser return null Other browsers return document
 console.log(target);
}

load events occur not only on document objects, but also on various external resources. Web browsing is a process of loading various resources, such as images (image), style sheets (style sheet), scripts (script), videos (video), audio (audio), Ajax requests (XMLHttpRequest) and so on. These resources, along with document objects, window objects, and XMLHttpRequestUpload objects, trigger load events

[Note] If the page is loaded from the browser cache, the load event is not triggered

Image and frame iframe can also trigger load events

[Note] Specify the event before specifying the src property of the image, which is downloaded after the src property is set


var img = new Image();
img.onload = function(){
 document.body.appendChild(img);
}
img.src="http://sandbox.runjs.cn/uploads/rs/26/ddzmgynp/chunfen.jpg";

<iframe id="test" src="http://cnblogs.com" frameborder="0"></iframe>
<script>
test.onload = function(){
 console.log(666);
}
</script>

The script element can also trigger the load event so that the developer can determine whether the dynamically loaded javascript file has finished loading. Unlike images, the javascript file is downloaded only after the src attribute of the script element is set and added to the document. In other words, the order in which you specify the src property and the event handler is not important

[Note] IE8-This usage is not supported by browsers


var script = document.createElement('script');
script.onload = function(){
 console.log(666);
}
document.body.appendChild(script);
script.src=http://files.cnblogs.com/files/xiaohuochai/excanvas.js;

Similarly, an link element can trigger an load event without compatibility issues. Similar to script, the style sheet is not downloaded until the href attribute is specified and the link element is added to the document

Similarly, an link element can trigger an load event without compatibility issues. Similar to script, the style sheet is not downloaded until the href attribute is specified and the link element is added to the document

error

The load event fires when the load succeeds, whereas the error event, in contrast, fires when the load fails. Any element that can trigger an load event can also trigger an error event

Any error that is not handled by try-catch triggers the error event of the window object

The error event can receive three parameters: the error message, the URL where the error is located, and the line number. In most cases, only error messages are useful, because URL simply gives the location of the document, and line numbers refer to lines of code that may come from either embedded javascript code or external files

To specify an onerror event handler, you can use either the DOM Level 0 technology or the standard format for DOM Level 2 events


//DOM0 Grade 
window.onerror = function(message,url,line){
 alert(message);
}
//DOM2 Grade 
window.addEventListener("error",function(message,url,line){
 alert(message);
});

Whether the browser displays standard error messages depends on the return value of onerror. If the return value is false, an error message is displayed in the console; If the return value is true, the


// The console displays an error message 
window.onerror = function(message,url,line){
 alert(message);
 return false;
}
a;
// The console does not display error messages 
window.onerror = function(message,url,line){
 alert(message);
 return true;
}
a;

This event handler is the last line of defense against browsers reporting errors. Ideally, it should not be used whenever possible. As long as the try-catch statements are used properly, no errors are delivered to the browser and no error events are triggered

Images also support error events. The error event is triggered as long as the URL in the src feature of the image does not return a recognizable image format. The error event follows the DOM format and returns an event object that targets the image

When the error event occurs, the image download process has ended, that is, it cannot be downloaded again. However, in the error event, you can reset the src property of the image to point to the address of the alternate image


var image = new Image();
document.body.appendChild(image);
image.onerror = function(e){
 image.src = 'smileBackup.gif';
}
image.src = 'smilex.gif';

abort

This event is triggered when the loading of an element is aborted (for example, when the ESC key is pressed during loading to stop loading), which is often used for image loading

[Note] Only IE browser supports


var image = new Image();
image.onabort = function(){
 console.log(111);
}
document.body.appendChild(image);
image.src = 'http://sandbox.runjs.cn/uploads/rs/26/ddzmgynp/chunfen.jpg';

unload

Corresponding to the load event is the unload event, which is triggered after the document is completely unloaded. 1, this event is triggered when the page is refreshed

The chrome/firefox/safari browser blocks dialog boxes such as alert, and the IE browser blocks console displays such as console. log ()


window.onunload = function(e){
 //chrome Report an error, firefox Silent failure, IE Eject 666
 alert(666);
}

window.onunload = function(e){
 //chrome And firefox Console display 666 , IE Silent failure 
 console.log(666);
}

beforeunload

The beforeunload event is triggered when a web page is closed or refreshed. It is generally used to prevent users from accidentally closing web pages

If the beforeunload event is to take effect, 1: 1 of the following two conditions must be met, and the event handler returns 1 true value; 2. The event object event. returnValue returns a true value. If both conditions are met at the same time, the first condition shall prevail

chrome/safari/firefox does not display the specified text in the dialog box, only the default text. The IE browser displays the return value or returnValue value in the dialog box


var img = new Image();
img.onload = function(){
 document.body.appendChild(img);
}
img.src="http://sandbox.runjs.cn/uploads/rs/26/ddzmgynp/chunfen.jpg";
0

DOMContentLoaded

The onload event of window is triggered when all of the 1 clips in the page have been loaded, but this process can be cumbersome because there are too many external resources to load. The DOMContentLoaded event is triggered after the complete DOM tree is formed, regardless of whether the image, javascript file, CSS file, or other resources have been downloaded. Unlike load events, DOMContentLoaded supports adding event handlers early in the page download, which means that users can interact with the page as early as possible

[Note] The javascript scripts for Web pages are executed synchronously, so the listener function that defines DOMContentLoaded events should be placed at the front of all scripts. Otherwise, the DOMContentLoaded event will be delayed once script 1 is blocked

To handle the DOMContentLoaded event, you can add an event handler for either document or window, and although this event bubbles to window, it actually targets document

[Note] IE8-Browser does not support this event


var img = new Image();
img.onload = function(){
 document.body.appendChild(img);
}
img.src="http://sandbox.runjs.cn/uploads/rs/26/ddzmgynp/chunfen.jpg";
1

For browsers that do not support this event, such as IE8-Browser, you can set a timeout call of 0 milliseconds during page load, and it must be the first timeout call of the page


var img = new Image();
img.onload = function(){
 document.body.appendChild(img);
}
img.src="http://sandbox.runjs.cn/uploads/rs/26/ddzmgynp/chunfen.jpg";
2

readystatechange

readystatechange events occur when Document objects and XMLHttpRequest objects change their readyState properties

The purpose of this event is to provide information about the loading status of a document or element. Each object that supports readystatechange events has one readyState attribute, which may contain one of the following five values


uninitialized( Uninitialized ) Object exists but has not been initialized  
loading( Loading ) Object is loading data 
loaded( Load complete ) Object loading data completion 
interactive( Interactive ) You can manipulate the object, but it is not fully loaded yet 
complete( Finish ) Object has finished loading 

These states seem intuitive, but not all objects go through these phases of readyState. In other words, if a stage does not apply to an object, it is entirely possible for the object to skip the stage; It does not specify which stage applies to which object. Obviously, this means that readystatechange events are often less than 4 times, and the values of readyState attributes are not always continuous

For an document, an readyState with a value of "interactive" triggers an readystatechange event at approximately the same time as an DOMContentLoaded. At this point, the DOM tree is loaded and you can safely manipulate it, so you enter the interaction (interactive) phase. But at the same time, images and other external files are not necessarily available


var img = new Image();
img.onload = function(){
 document.body.appendChild(img);
}
img.src="http://sandbox.runjs.cn/uploads/rs/26/ddzmgynp/chunfen.jpg";
4

When used with load Event 1, it is impossible to predict the sequence in which the two events will be triggered. In pages containing more or larger external resources, the interaction phase will be entered before the load event is triggered; In pages with fewer or smaller external resources, it is difficult to say that an readystatechange event will occur before an load event

Complicating the problem is that the interaction phase may occur before or after the completion phase, and the order cannot be ensured. In pages with more external resources, the interaction phase is more likely to appear before the completion phase; When the page contains fewer external resources, it is more likely that the completion phase will appear before the interaction phase. Therefore, it is necessary to detect both interaction and completion phases in order to get the best possible advantage


var img = new Image();
img.onload = function(){
 document.body.appendChild(img);
}
img.src="http://sandbox.runjs.cn/uploads/rs/26/ddzmgynp/chunfen.jpg";
5

For the above code, when the readystatechange event is triggered, the value of document. readyState is detected to see if it has entered the interaction phase or the completion phase. If so, remove the corresponding event handler to avoid executing at other stages

In addition, the IE10-browser supports triggering the readystatechange event for the script element and the link element to determine whether the external javascript or css file has been loaded


var img = new Image();
img.onload = function(){
 document.body.appendChild(img);
}
img.src="http://sandbox.runjs.cn/uploads/rs/26/ddzmgynp/chunfen.jpg";
6

var img = new Image();
img.onload = function(){
 document.body.appendChild(img);
}
img.src="http://sandbox.runjs.cn/uploads/rs/26/ddzmgynp/chunfen.jpg";
7

Related articles: