How to Link JavaScript to HTML
To link a JavaScript file to an HTML document, use the <script>
tag. You can also use this tag to embed JavaScript code within the HTML document.
Linking to an External JavaScript File
To link to an external JavaScript file, use <script src="myExternalFile.js"></script>
where myExternalFile.js is the location of the external file.
The above example links to an external JavaScript file. The location of the JavaScript file is provided as the value for the src
attribute. When the HTML file loads, the JavaScript file is also loaded.
Placement of the <script>
Tags
External JavaScript files are often linked to from the document <head>
but this is not a requirement. You can also place the link within the document <body>
element. In fact, more and more developers are linking to their JavaScript files from the bottom of the HTML document (just before the closing </body>
tag) for performance reasons. Doing this allows the rest of the HTML page to load without having to wait for external JavaScript resources to be downloaded first.
However, there may be times when placing it in the <head>
is more appropriate (for example, if the JavaScript needs to be available to the page as it's loading).
Embedded JavaScript
You can also use the <script>
element to embed JavaScript code into the HTML page.
This second example uses exactly the same JavaScript as the first example (only the text has changed). The only difference is that the JavaScript is now embedded into the HTML document, as opposed to being located in an external file.
Again, this doesn't necessarily need to be in the <head>
element — it could be located anywhere within the HTML document.
The type
Attribute
You can use the type
attribute to explictly state the script type. If you omit this attribute the script will be treated as JavaScript. So there is no need to use this attribute if the script is in JavaScript.
If the script is not written in JavaScript, you should use the type
attribute to explicitly state the type of script.