Chapter 2

JavaScript in HTML

WHAT’S IN THIS CHAPTER?

  • Using the <script> element
  • Comparing inline and external scripts
  • Examining how document modes affect JavaScript
  • Preparing for JavaScript-disabled experiences

The introduction of JavaScript into web pages immediately ran into the Web’s predominant language, HTML. As part of its original work on JavaScript, Netscape tried to figure out how to make JavaScript coexist in HTML pages without breaking those pages’ rendering in other browsers. Through trial, error, and controversy, several decisions were finally made and agreed upon to bring universal scripting support to the Web. Much of the work done in these early days of the Web has survived and become formalized in the HTML specification.

THE <SCRIPT> ELEMENT

The primary method of inserting JavaScript into an HTML page is via the <script> element. This element was created by Netscape and first implemented in Netscape Navigator 2. It was later added to the formal HTML specification. There are six attributes for the <script> element:

  • async — Optional. Indicates that the script should begin downloading immediately but should not prevent other actions on the page such as downloading resources or waiting for other scripts to load. Valid only for external script files.
  • charset — Optional. The character set of the code specified using the src attribute. This attribute is rarely used, because most browsers don’t honor its value.
  • defer — Optional. Indicates that the execution of the ...

Get Professional: JavaScript® for Web Developers, Third Edition now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.