Project development for a long time, especially the long-term use of development tools shortcuts to achieve HTML default documents, suddenly use TXT to create HTML documents, but the location of the label has produced uncertainty.
Here are the most common HTML document tag storing templates:
<! DOCTYPE HTML> < HTML lang="en"> <title> <meta charset=" UTF-8 "> <style> </style> </head> <body> <p> Welcome to... . < / p > < script > console log (' page shows success ') < / script > < / body > < / HTML >Copy the code
Script tag location
When javascript is loaded, it is executed immediately. After the execution, the body begins to render. Therefore, the location of the script block in different locations is very important.
When you need to get the DOM node in the document
- If the script tag is placed in the head, the node will not get it
- Get it normally before the body closing tag
The DOM has not yet been generated, so you cannot put the associated JS logic for the DOM element you want to access before the body
<! DOCTYPE HTML> < HTML lang="en"> <title> <meta charset=" UTF-8 "> <style> </style> <script> let theP = document.getElementByTagName('p')[0]; Console. log(theP) // undefined </script> </head> <body> <p> </p> <script> console.log(' page displayed successfully '); let pTag = document.getElementByTagName('p')[0]; console.log(pTag) // </script> </body> </html>Copy the code
Js code execution blocks page rendering
Js enters an infinite loop, the console keeps printing 1, the page keeps loading, and the HTML tag cannot be rendered
<head>
<script>
while(true){
console.log(1)
}
</script>
<head>
Copy the code
The script tag if you want to put it in the head tag
Page implementation effect, need to load some JS script in advance, can use the following way to achieve
window.onload=function(){}
Copy the code
or
documnet.ready=function(){}
Copy the code