Don’t write
<script></script>
Copy the code
The first thing you must do is block DOM parsing
<! DOCTYPE html> <html lang="en">
<head>
<meta charset="UTF-8"> <title>JS blocks DOM parsing </title> </head> <body> <script> console.log(document.getelementbyid ("test"));
</script>
<p id="test">world</p>
</body>
</html>
Copy the code
The result printed by the above code is NULL, indicating that the JS code execution did not parse to the P tag id test, so generally, the script tag is placed at the bottom of the body tag
Second, it doesn’t necessarily block DOM rendering
- Javascript code that is inline blocks DOM rendering
<! DOCTYPE html> <html lang="en">
<head>
<meta charset="UTF-8"</title> </head> <body> <p> Hello </p> <script>for(let i = 0 ; i < 2000000000; i++) {
let a = 1;
}
console.log("over");
</script>
<p>world</p>
</body>
</html>
Copy the code
The code above blocks DOM rendering when it encounters inline JS code, so hello and world don’t appear until the page prints over
- External JS code does not block DOM rendering all the time
<! DOCTYPE html> <html lang="en">
<head>
<meta charset="UTF-8"> <title>JS will block DOM rendering </title> </head> <body> <p>hello</p> <script SRC ="script.js"></script>
<p>world</p>
</body>
</html>
Copy the code
for(let i = 0; i < 2000000000; i++) {
let a = 1;
}
console.log("over");
Copy the code
The above code will trigger a rendering when it encounters a script tag, so the page will see Hello first, then DOM rendering will be blocked, and script.js will be loaded and executed, so the world will be seen only after the over prints
After deciding whether to block DOM rendering, the last step is to load and execute the script
Async and defer
<script async src="script.js"></script>
<script defer src="script.js"></script>
Copy the code
Async and defer are only valid for external scripts
It’s a classic picture
Async is often used for scripts without any dependencies that are downloaded and executed as soon as possible