Home > Web Front-end > JS Tutorial > body text

How to use JavaScript's onload event

不言
Release: 2018-12-27 17:09:23
Original
8055 people have browsed it

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() {
// 加载完成后需要立即处理的事件
}
Copy after login

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("页面已加载!");
};
Copy after login

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;
Copy after login

Execute when loading the image

The code is as follows

var img = new Image();
img.onload = function() {
  alert("图像已加载!");
};
img.src = 'img/mouse.png';
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!