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:

// Your JavaScript code goes here

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 ...

Get JavaScript: The Definitive Guide, 6th 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.