Embedding JavaScript in HTML
Client-side JavaScript code is embedded within HTML documents in a number of ways:
Between a pair of
<script>
and</script>
tagsFrom an external file specified by the
src
attribute of a<script>
tagIn an event handler, specified as the value of an HTML attribute such as
onclick
oronmouseover
As the body of a URL that uses the special
javascript:
protocol
The following sections document each of these JavaScript embedding techniques in more detail. Together, they explain all the ways to include JavaScript in web pages -- that is, they explain the allowed structure of JavaScript programs on the client side.
The <script> Tag
Client-side
JavaScript scripts are part of an HTML file and are coded within
<script>
and </script>
tags. You may place any number
of JavaScript statements between these tags; they are executed in
order of appearance, as part of the document loading process.
<script>
tags may appear in either the
<head>
or <body>
of
an HTML document.
A single HTML document may contain
any number of nonoverlapping pairs of
<script>
and
</script>
tags. These multiple, separate scripts are executed in the order in which they appear within the document. While separate scripts within a single file are executed at different times during the loading and parsing of the HTML file, they constitute part of the same JavaScript program: functions and variables defined in one script are available to all scripts that follow in the same file. For example, ...
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.