Cover by David Flanagan

Safari, the world’s most comprehensive technology and business learning platform.

Find the exact information you need to solve a problem on the fly, or go deeper to master the technologies and skills you need to succeed

Start Free Trial

No credit card required

O'Reilly logo

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

Find the exact information you need to solve a problem on the fly, or go deeper to master the technologies and skills you need to succeed

Start Free Trial

No credit card required