JavaScript is executed client-side, on the browser. Like CSS, it can be written either inline, embedded, or linked, and (just like CSS) those methods are in order of preference in terms of power and adaptability. A link to a JavaScript file is often written inside the <head>
section of the page on which it is used:
<head>
<title>An HTML Page With Linked Javascript<title>
<script src="assets/scripts/prettify.js"></script>
</head>
There are a few possible downsides to this:
- Page rendering may be halted until the script is loaded and executed.
- A script written in the
<head>
may attempt to modify DOM elements that have not yet appeared on the page.
Alternatively, links to JavaScript files can be placed at the end of the document, typically just before the closing </body>
tag.
<script src="assets/scripts/prettify.js"></script>
</body>
</html>
…thus avoiding both issues.
JavaScript files must have a .js extension in the filename. (You will occasionally see a language
attribute used when linking to a JavaScript file, but that is deprecated and invalid in HTML.)
It is also possible to link to a JavaScript file outside your own domain: this is frequently done when using JavaScript frameworks such as jQuery to centralize code and potentially speed up load times. (Cross-domain files will load in a seperate simultaneous “stream” from the rest of the page, and will be cached by the browser: if the user has previously visited a site that uses the same technique for the same file, the cached version of the file will be used, rather than downloading it again.)
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js">
</script>
The second and less preferable option is to write the JavaScript embedded, again in the <head>
section, or, preferably, at the bottom of the page:
<script>
/* JavaScript code goes here */
</script>
Note that you cannot write HTML or CSS directly inside JavaScript; like CSS, using another language between the opening and closing <script>
tags, or in the linked JavaScript file, will cause it to stop working.
You do not, as a general rule, write JavaScript code inline, for reasons I will cover shortly.
Photograph by Tekke, used under a Creative Commons license
Enjoy this piece? I invite you to follow me at twitter.com/dudleystorey to learn more.