Running JavaScript Via Browser
The JavaScript file, for the most part, is run whenever the JS file is run or when the <script>
tag is encountered in the HTML file.
- When including the JavaScript at the top of the HTML file, many DOM manipulation methods will not work because the JS code is being run before the nodes are created in the DOM.
- The simplest way to fix this is to include the JavaScript at the bottom of your HTML file so that it gets run after the DOM nodes are parsed and created.
<body>
<!-- HTML code body -->
<!-- External JS - at the end of HTML body -->
<script src="index.js"></script>
</body>
<body>
<!-- HTML code body -->
<!-- Internal JS - at the end of HTML body -->
<script >
/*
JavaScript code body
...
*/
</script>
</body>
Alternatively, you can link the JavaScript file in the <head>
of your HTML document and include the defer
keyword to load the file after the HTML is parsed.
<head>
<script src="index.js" defer></script>
</head>