Adding Script
To add a script to a web page, HTML files use the script
tag. In its src
attribute you should include a link to an external JavaScript file.
To link JavaScript from an external file:
- Create a
.js
file and place it in thejs
subfolder. - Then specify the path to the script file in the
src
attribute of thescript
tag.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>JavaScript is fun!</title>
</head>
<body>
<!-- content-->
<script src="js/script.js"></script>
</body>
</html>
Storing a JavaScript file in the js
folder is not mandatory, but it is good practice.
If the script is added within <head>
, the page stops rendering until loading and executing the script. Browsers load and display HTML step by step. When there is a <script>
tag with no additional attributes, the script is executed first, and only then the rest of the HTML file code is processed. Therefore, the script should be added before the <body>
closing tag, after all content, as in the example.
Multiple scripts
When linking several JavaScript files to a page, the interpreter processes them in the order in which they are specified in the HTML file.
<script src="js/script-1.js"></script>
<script src="js/script-2.js"></script>