Contents

Scripts may be placed in either "external" files, "internal" HTML tags, or "inline" HTML attributes. External files are widely accepted as the best among these because:

They are easier to read (because the brain doesn't have to switch "modes").

The browser can reuse them (because they are addressable separate from the HTML).

However, situations do exist where the others are appropriate. For example, if something needs to happen directly after a certain image loads, an external or internal script is insufficient. And external scripts are rather inconvenient on programming-oriented message boards, so the recipients of internal scripts are expected to externalize them.

Tags work in much the same way as files, except the browser receives the entire page in one request (and the programmer must sift through the irrelevant language, either HTML or JavaScript, in order to do anything) if tags are used. Here is index.html:

You may have noticed that this script tag contains an HTML comment which contains the JavaScript. This is to help older browsers which were released before the tag was known and would display the JavaScript as text on the page. The two slashes are a JavaScript comment which hides the HTML comment's terminator (-->) from JavaScript-capable browsers which would otherwise flag it as invalid; the initializer (<!--) is not known to cause a problem.

Why the same script tag doesn't work in the head is left as an exercise for the reader.

Any HTML attribute whose name begins with on is an event-handler. Event-handlers allow JavaScript much greater flexibility than it would have without them; they notify a script that a certain thing has happened and provide some contextual information. However, note that they are also easy to use from external and internal scripts. Here is index.html: