Training Guide: Programming in HTML5 with JavaScript and CSS3 Ebook

(Nora) #1

Lesson 2: Writing, testing, and debugging JavaScript CHAPTER 3 101


Next is the beginning of an HTML comment. Notice that the bottom contains a JavaScript
comment and an HTML end comment. This is the recommended method for dealing with
browsers that don’t support the script element. Without the comment, the browser would just
render the JavaScript source to the screen.
This script defines an add function. An alert is executed that calls the add function and
sends the results to the alert function. Notice that the call to the alert function is not within a
function; this call is inline. As this HTML document is being loaded, the browser reaches the
alert call and, because it’s inline, the alert call is immediately executed.
The following is an example of a <script> element referencing an external JavaScript file:
<script type="text/javascript" src="Scripts/tests.js"></script>

The src attribute references the external JavaScript file. When the src attribute is included,
the content of the <script> element must be empty. It’s important to use an explicit end tag
to prevent problems in some browsers.
For external JavaScript files, the following attributes can also be used:
■■async A Boolean attribute specifying that the script is executed asynchronously while
the page continues the parsing.
■■defer A Boolean attribute specifying that the script is executed after the page has
finished parsing.
If async and defer are not present, the script is fetched when the HTML parser reaches the
script element and is executed immediately, before the browser continues parsing the page.
For large HTML documents and large JavaScript files, the result is that the page takes much
longer to render.

NOTE USING ASYNC AND DEFER
Be careful when using async and defer. First, not all browsers support these attributes yet.
Second, when you are loading many external JavaScript files that depend on one another,
using these attributes can change the execution order.

Handling browsers that don’t support JavaScript


In addition to placing HTML comments around script blocks to keep your JavaScript source
from being rendered to the screen when a browser does not support the <script> element,
you can use the <noscript> element to specify alternate content to display. The following is an
example of the <noscript> element:
<script type="text/javascript">
<!--
function Add(x, y) {
return x + y;
}
Free download pdf