Where to Insert
Learn where and how to place JavaScript in your HTML.
JavaScript can be placed in the head and body section
We can place JavaScript both in the <head>
and <body>
sections of a page by using the <script></script>
elements.
JavaScript can be external from the HTML file
JavaScript can also be placed in external files just like external CSS. External scripts are practical when the same code is used in many different web pages.
To use an external script, put the name of the script file in the src (source) attribute of a <script>
tag. Users can place an external script reference in <head>
or <body>
. The script will behave as if it was located exactly where the <script>
tag is located.
JavaScript files have the file extension of .js
.
External JavaScript cannot contain <script>
tags.
The use of <script>
tag will be inside the html file.
Connecting to external JavaScript
Advantages of using external JavaScript
Placing scripts in external files offer some advantages like:
- It separates HTML tags and JavaScript code.
- It makes HTML and JavaScript easier to read and maintain.
- Cached JavaScript files can speed up page loads.
External References
An external references can be referenced in 3 different ways.
- With a full URL website link.
- With a file path
/js/javascript.js
- With any path
javascript.js
Last updated on