O'Reilly logo

JavaScript: The Definitive Guide, 6th Edition by David Flanagan

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Embedding JavaScript in HTML

Client-side JavaScript code is embedded within HTML documents in four ways:

  • Inline, between a pair of <script> and </script> tags

  • From an external file specified by the src attribute of a <script> tag

  • In an HTML event handler attribute, such as onclick or onmouseover

  • In 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:

<script><![CDATA[
// Your JavaScript code goes here

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required