HTML and CSS Reference
In-Depth Information
INSERTING JAVASCRIPT INTO HTML5 PAGES
JavaScript programs are placed in the head of a Web page because that part of the Web page
loads i rst, so it's ready when the rest of the page loads. h ey act very much like CSS3 scripts,
and like CSS3 scripts, they can be placed in other places than the page's head. However,
for this chapter, I'll keep it simple and all JavaScript will be in the head. For example, try
the following program ( js1.html in this chapter's folder at www.wiley.com/go/
smashinghtml5 ).
<! DOCTYPE HTML >
< html >
< head >
< meta http - equiv = ”Content-Type” content = ”text/html; charset=UTF-8” >
< script type = ”text/javascript” >
document . write ( “A chat with HTML5 is taking place shortly....” );
</script>
< title > First JavaScript </ title >
</ head >
< body >
</ body >
</ html >
When you test the program, you'll see text on your page and nothing else. h e key to under-
standing the relationship between HTML5 and JavaScript is in the function: document.
write() . h e document refers to the Web page, and write() is a method that tells the
Web page what to do. In this case, write() instructs the program to write the text in
quotation marks to the Web page.
234
JAVASCRIPT IN EXTERNAL FILES
Just like CSS3 i les, you can create JavaScript programs in text i les and save them externally.
h e .js extension is used to identify JavaScript i les. For example, the following JavaScript
program is just one line:
document.write ( “This is from an external file...” );
Save it as externalJS.js in a text-i le format. Next, enter the following HTML5 program
and save it in the same folder as the externalJS.js program. h e key part of the page is
the <script> tag that's used to specify the JavaScript program to use.
<! DOCTYPE HTML >
< html >
< head >
< script src = ”externalJS.js” ></ script >
< meta http - equiv = ”Content-Type” content = ”text/html; charset=UTF-8” >
< title > External JavaScript </ title >
</ head >
< body >
</ body >
 
Search WWH ::




Custom Search