Home  >  Article  >  Web Front-end  >  How to use JavaScript's onload event

How to use JavaScript's onload event

不言
不言Original
2018-12-25 17:11:368100browse

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.

How to use How to use How to use JavaScripts onload events onload events onload event

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

How to use How to use How to use JavaScripts onload events onload events onload event

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

How to use How to use How to use JavaScripts onload events onload events onload event

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn