Home > Article > Web Front-end > How to use JavaScript's onload event
onload is an event used when processing documents such as HTML. It occurs immediately after the page and all images and other resources are loaded. In this article, we will introduce in detail the use of the onload event in How to use How to use How to use JavaScripts onload events onload events onload event. method.
Let’s first take a look at the basic writing method of onload event
obj.onload = function() { // 加载完成后需要立即处理的事件 }
For obj, it can be specified as window or HTML body, img and other elements.
Let’s look at a specific example
Executed when loading the page
If you execute the following code, you can read the window object Processing
window.onload = function() { alert("页面已加载!"); };
The running effect is as follows
The following code achieves the same effect
function load() { alert("页面已加载!"); } window.onload = load;
Execute when loading the image
The code is as follows
var img = new Image(); img.onload = function() { alert("图像已加载!"); }; img.src = 'img/mouse.png';
The running effect is as follows
Finally let’s take a look at the precautions for using the onload event
The handler of the event with onload cannot set multiple event handlers for the same event of the same element; if you want to set multiple event handlers for the same event of the same element, then we can use addEventListener .
Also, if you want to execute the process immediately after reading the page and all resources (such as images), use onload, but if you want to execute the process without waiting for reading, you need to use DOMContentLoaded.
The above is the detailed content of How to use JavaScript's onload event. For more information, please follow other related articles on the PHP Chinese website!