Do we always have to add JavaScript in the HTML file directly?


In this exercise, the JavaScript code is placed inside the <script> tags. Do we always have to add the JavaScript in the HTML file directly in this manner?


No, you do not always have to add JavaScript directly into the HTML code using the <script> tags.

Another way you can apply JavaScript to a webpage is by linking to an external JavaScript file instead. This can be a good idea because it will keep the code separate, and apply the idea of “separation of concerns”. However, you are free to choose either method to add your JavaScript code.

To link an external JavaScript file to the HTML, we can use the <script> tag with the src attribute. For example, this will link a JavaScript file named “index.js” to the webpage:

<script src="index.js"></script>

This is usually added right before the closing </body> tag, due to how the browser would load the files.


Why can’t we link the index.js file using the href attribute instead of src attribute? Like we did for the CSS file? Thanks in advance!


Well, I looked around for a good answer/explanation, and most answers I found refer back to this topic on stackoverflow:
Read at least the first 3 answers. Explains it pretty well.