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


#1

Question

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?

Answer

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.