The HTML script element allows you to embed JavaScript into an HTML document. Often script elements are placed within the head element, and, in fact, this placement was often stated as a requirement. Today, however, script elements are used within the head element as well as in the body of web pages.
The format of the script element is very simple:
<script> (insert your JavaScript here) </script>
Here’s an example of an HTML document with a script tag containing JavaScript. In this case, however, the script element is placed at the bottom of the body element.
<!DOCTYPE html> <html> <head> <title>Hello, HTML!</title> </head> <body> <h1>Let’s Count to 10 with JavaScript!</h1> <p id="theCount"></p> <script> var count = 0; while (count < 10) { count++; document.getElementById("theCount").innerHTML += count + "<br>"; } </script> </body> </html>
Script placement and JavaScript execution
Web browsers normally load and execute scripts as they are loaded. A web page always gets read by the browser from the top down, just as you would read a page of text. Sometimes you’ll want to wait until the browser is done loading the contents of the web page before the script runs.
Above, this was accomplished by using the onload event attribute in the body element. Another common way to delay execution is to simply place the code to be executed at the end of the code.