Submodule 6.2: Simple JavaScript file
Submodule 6.2: Simple JavaScript file
- JavaScript in HTML file
- alert interaction
- Variables
- prompt interaction
- Comments in JavaScript
- Developer tools (console)
Where do we put JavaScript code in the HTML code;
JavaScript can be connected to the HTML file using three different ways:
- Write your JavaScript at the head of the HTML document
- Write your JavaScript at the end of the body of the HTML document
- Use an external sheet and reference your JavaScript either at the head or at the end of the body of the HTML document
In the HTML file
When we use the first or the second way, we need to wrap our code inside script tags, <script>.. </script>.
In general, when we write our JavaScript directly at the HTML is preferable to put it at the end of the body rather than at the head. This is because we want our page to have completed the loading so the JavaScript can function properly.
<!DOCTYPE html>
<html>
<head>
. . . <script> load JavaScript libraries here </script>. . .
</head>
<body>
. . . <script> your JavaScript code typically goes at the end of body </script>. . .
</body>
</html>
External file
When we use an external sheet we do NOT put the script tags. We just write our JavaScript. Again we prefer to reference our JavaScript at the end of the HTML body.
<!DOCTYPE html>
<html>
<head>
. . . <script> load JavaScript libraries here </script>. . .
</head>
<body>
. . . <script type="text/javascript" src="js/myscript.js"></script>. . .
</body>
</html>
Over the three available ways, the 3rd one, usage of an external sheet, is the preferable way.
One reason for that is because, with this, we separate markup from code. Moreover, it is easier to read the files and do changes. Also, it helps the page to load more quickly.
For more information: https://www.w3schools.com/js/js_whereto.asp