简体   繁体   中英

“onload” in <body> tag of HTML and JavaScript?

I want to know if "onload" is attribute of <body> tag of HTML. I saw this code snippet while I was going through a book (for learning Java Script).

<html>
    <body onload="alert('hi')";>
      ...
    </body>
</html>

I know that <body> tag is part of HTML specification. And for an HTML element we can have attributes. Going by this, does it mean onload is <body>'s attribute? Or is it part of JavaScript? How is this merger possible?

If so, does it also mean when HTML was initially developed, did the creator thought that there might be some event driven stuff to be applied (by some other language?).

Can anyone help me in understanding this? Till this point the book/si have referred it didn't throw any light on what my doubt is, hence asking this question.

One of the ways to attach event handlers to any HTML element is by giving it an attribute named onEVENTNAME . The value of such an attribute is a string of Javascript that will be executed when the event is triggered on the element. You've almost certainly seen things like

<button onclick="doSomething()">

This is the same kind of thing.

The HTML specification of Global Attributes says that onload (among many other onXXX attributes) can be used in any HTML element. There are also a number of onXX attributes that are specific to the <body> element .

The only thing special about the <body> element in this regard is that some of the event handlers are assigned to the window object. So your example is roughly equivalent to:

window.onload = function() {
    alert('hi');
};

The onload attribute fires when an object has been loaded. onload is most often used within the <body> element to execute a script once a web page has completely loaded all content (including images, script files, CSS files, etc.).

The syntax is,

<element onload="script"> 

This below few html tags for supported like

<body>, <frame>, <img>, <link>, <script> and <style>

Example:

<img src="image.gif" onload="alert('image loaded')">

Thus the above code onload on an element, Alert "Image loaded" immediately display after an image has been loaded.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM