User:Jesdisciple/JavaScript/Placing the Code

At the end of the last chapter, you were (hopefully) wondering what the below code fragment means. This chapter is about how to tell the browser, using HTML, that it needs to start thinking in JavaScript.

The element
All JavaScript, when placed in an HTML document, needs to be within a  element. A  element is used to link to an external JavaScript file, or to contain inline scripting (script snippets in the HTML file). A  element to link to an external JavaScript file looks like:

while a  element that contains inline JavaScript looks like:

Inline scripting has the advantage that both your HTML and your JavaScript is in one file, which is convenient for quick development and testing. Having your JavaScript in a separate file is recommended for JavaScript functions which can potentially be used in more than one page, and also to separate content from behaviour.

For those wondering, yes you can move the  tag to other sections of your HTML deocument; however, placing it in the   is sufficient for almost all cases. A much less useful nugget is that you can tell the browser to use a different scripting language.

Inline JavaScript
Using inline JavaScript allows you to easily work with HTML and JavaScript within the same page. This is commonly used for temporarily testing out some ideas, and in situations where the script code is specific to that one page.

Inline HTML comment markers
The inline HTML comments are to prevent older browsers that do not understand JavaScript from displaying it in plain text.

The  is a comment delimiter, which prevents the end comment tag   from being interpreted as JavaScript.

The usage of comment markers is rarely required nowdays, as the browsers that do not recognise JavaScript are virtually non-existent. These early browsers were Mosaic, Netscape 1 and Internet Explorer 2. From Netscape 2.0 in December 1995 and Internet Explorer 3.0 in August 1996 on, browsers were able to interprete JavaScript.

Inline XHTML JavaScript
In XHTML, the method is somewhat different:

Note that both the  tags are commented out. This prevents the browser from mistakenly interpreting strings with XHTML tags as if they were actual XHTML tags.

Linking to external scripts
JavaScript is commonly stored in a file so that it may be used by many web pages on your site. This makes it much easier for updates to occur and saves space on your server. This method is recommended for separating behavior (JavaScript) from content ((X)HTML) and it prevents the issue of incompatibility with inline comments in XHTML and HTML.

Add  to the opening   tag. Replace script.js with the path to the .js file containing the JavaScript.

Because the server provides the content type when the file is requested, specifying the type is optional when linking to external scripts. It's still advised to specify the type as text/javascript, in case the server isn't set up correctly, and to prevent HTML validation complaints.