Coding with JavaScript For Dummies
Book image
Explore Book Buy On Amazon

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:

 (insert your JavaScript here)

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>
 <title>Hello, HTML!</title>
 <h1>Let’s Count to 10 with JavaScript!</h1>
 <p id="theCount"></p>
 var count = 0;
 while (count < 10) {
 document.getElementById("theCount").innerHTML +=
count + "<br>";

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.

Limitations of JavaScript in

About This Article

This article is from the book:

About the book authors:

Chris Minnick is an accomplished author, trainer, and web developer who has worked on web and mobile projects for both small and major businesses. Eva Holland is an experienced writer and trainer who has designed and taught online, in-person, and video courses. They are cofounders of WatzThis?

This article can be found in the category: