Execution of JavaScript Programs
The previous section discussed the mechanics of integrating JavaScript code into an HTML file. Now we move on to discuss exactly how that integrated JavaScript code is executed by the JavaScript interpreter. The following sections explain how different forms of JavaScript code are executed. While some of this material is fairly obvious, there are a number of important details that are not so obvious.
Scripts
JavaScript
statements that appear between <script>
and
</script>
tags are executed in order of
appearance; when more than one script appears in a file, the scripts
are executed in the order in which they appear. If a script calls
document.write( )
, any text passed to that method
is inserted into the document immediately after the closing
</script>
tag and is parsed by the HTML
parser when the script finishes running. The same rules apply to
scripts included from separate files with the src
attribute.
The detail that is not so obvious, but
is nevertheless important to remember, is that execution of scripts
occurs as part of the web browser’s HTML parsing process. Thus,
if a script appears in
the <head>
section
of an HTML document, none of the
<body>
section of the document has been defined
yet. This means that the JavaScript objects that represent the
contents of the document body, such as Form and Link, have not been
created yet and cannot be manipulated by that code.
Your scripts should not attempt to manipulate objects that have not ...
Get JavaScript: The Definitive Guide, Fourth Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.