Embedding JavaScript in HTML
Client-side JavaScript code is embedded within HTML documents in four ways:
Inline, between a pair of
<script>and</script>tagsFrom an external file specified by the
srcattribute of a<script>tagIn an HTML event handler attribute, such as
onclickoronmouseoverIn a URL that uses the special
javascript:protocol.
The subsections that follow explain each of these four
JavaScript embedding techniques. It is worth noting, however, that
HTML event handler attributes and javascript:
URLs are rarely used in modern JavaScript code (they were somewhat
common in the early days of the Web). Inline scripts (those without a
src attribute) are also less common
than they once were. A programming philosophy known as
unobtrusive JavaScript argues that content (HTML)
and behavior (JavaScript code) should as much as possible be kept
separate. According to this programming philosophy, JavaScript is best
embedded in HTML documents using <script> elements with src attributes.
The <script> Element
JavaScript code can appear inline within an HTML file between
<script> and </script> tags:
<script>// Your JavaScript code goes here</script>
In XHTML, the content of a <script> element is treated like any
other content. If your JavaScript code contains the < or & characters, these characters are
interpreted as XML markup. For this reason, it is best to put all
JavaScript code within a CDATA section if you are using XHTML. The
leading // ensure that even the oldest browsers will ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access