onload event

 The onload event is designed to trigger a specific JavaScript function to perform a specific task after the web page is loaded. Common applications such as displaying a dialog window after the web page is loaded, loading a frame, displaying welcome, and jumping out of the second-level web page. .. etc. Although this technique is quite easy to use, using too much may cause the page loading completion time to prolong and affect the web page experience. There are usually two ways to write onload. The first is to write directly in the <body> tag at the beginning of HTML. This way of writing does not need to be brought out by JavaScript to operate, and the second is to bring out through the window object method of JavaScript. The function of onload, both are also used to trigger specific functions of JavaScript to perform tasks.


Basic syntax of onload

onload = "javascript function to be triggered"


The trigger function in quotation marks is necessary. After all, onload is an event , and its biggest function is to tell a specific function to start working. The following is divided into two common writing examples. Since onload will be executed immediately after the web page is loaded, this The sample output on the page is the result of execution.

Example 1: Write onload directly in the <body> tag

<script language="javascript">
function ShowHello(){
    document.getElementById('ShowBox').innerHTML='Hello';
}
</script>
<body onload="ShowHello()">
<span id="ShowBox "></span>
</body>
Example output
Hello
The example directly writes the onload event in the <body> tag. When the web page is loaded into the <body> tag, the browser will know that the ShowHello function will be triggered after the loading is complete. At this time, the onload work is actually completed. , The job of displaying "Hello" is done by the ShowHello function. Here is a little explanation of the operation in the ShowHello function. First obtain the span area of ​​the text to be displayed through document.getElementById of the DOM , and then write the string "Hello" through innerHTML , and you are done. Example 2: Write onload in JavaScript

<script language="javascript">
window.onload=ShowHello;
function ShowHello(){
    document.getElementById('ShowBox').innerHTML='Hello';
}
</script>
<body>
<span id="ShowBox" ></span>
</body>
Example output
Hello
In the second example, onload is not written in the <body> tag, but the JavaScript code area at the beginning is written first. The advantage of this is that the <body> tag is relatively clean. If the designer writes the entire JavaScript as a plug-in module In this way, the code of the entire webpage will be cleaner, which is also a pretty good design habit.

Post a Comment

0 Comments