When should I write window.onload in JavaScript
0. Reference materials
- The Art of JavaScript DOM Programming, p. 69
- The window.onload event in JS
- Why put the Script tag after the body tag and before the HTML tag?
1. In-page JS code
1.1 In-page JS code is written inside the head
If the script tag is written inside the head tag, the element inside the body will load later than the JS code, and some of the methods that get DOM elements will fail to get the element (returning null). The following sample code is intended to take the “I’m going red-hot! This text turns red, so it’s not working, and the console is reporting an error.
Sample code:test1.html
<! DOCTYPEhtml>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>JS code written inside the page and located in the head</title>
<script>
document.getElementById("text").style.color = "red";
</script>
</head>
<body>
<p id="text">I want to be in a trance!</p>
</body>
</html>
Copy the code
Effect and error message Modify the code, pluswindow.onload
.
<! DOCTYPEhtml>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>The in-page JS code is written inside the head</title>
<script>
window.onload = function () {
document.getElementById("text").style.color = "red";
};
</script>
</head>
<body>
<p id="text">I want to be in a trance!</p>
</body>
</html>
Copy the code
Final display
1.2 in-page JS code is written before the end of the body
If the in-page JS code is written before the , the other elements will be loaded before the JS code, so don’t write window.onload.
The sample code
<! DOCTYPEhtml>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>The in-page JS code is written before the body closing tag</title>
</head>
<body>
<p id="text">I want to be in a trance!</p>
<script>
document.getElementById("text").style.color = "red";
</script>
</body>
</html>
Copy the code
According to the effect
1.3 the conclusion
For in-page JS code:
- if
script
Label is written in thehead
Inside the tag, must be writtenwindow.onload
; - if
script
Label is written in the</body>
Before the tag, don’t write itwindow.onload
.
2. External chain JS code
Conclusion: External chained JS code needs to write window.onload wherever script tags are written.
- if
script
The label is herehead
Tag inside, then theJS
The code will beHTML
The document is loaded to the browser before. - if
script
The label is here</body>
Previously, there is also no guarantee which file ends loading first, as the browser may load multiple files at once.
Loading multiple files at once: Loading HTML files and linked JS files at the same time does not determine who finished downloading first.
- Because the documentation may be incomplete when the script loads, the model is also incomplete. Incomplete
DOM
.getElementsByTagName
And so on will not work properly.
This code will be executed as soon as the JavaScript file loads. If the JavaScript file is called from a
If the