Skip to content

Try our new Crash Courses!

Buy one of our new Crash Courses, now hosted on Teachable.

Link JavaScript file to HTML file

Summary

If your JavaScript file is in the same folder as your HTML file, add the following code to your HTML file (replace main.js with the name of your file if the name is different):

<script src="main.js" defer></script>

If your JavaScript file is in a separate folder, make sure the src attribute has the correct file path:

<script src="assets/js/main.js" defer></script>

Details

To link a JavaScript file to an HTML file, use the script element with the src attribute. The script element can be placed inside the head element if it includes the defer attribute:

<head>
  <!-- Other meta data goes here -->
  <script src="main.js" defer></script>
</head>

The src attribute specifies the file path of the JavaScript file. If the file is in the same folder, all you need is the file name in the src attribute. If the file is in a different folder, you need to include the folders that it’s in.

<head>
  <!-- Other meta data goes here -->
  <script src="js/main.js" defer></script>
</head>

If you have multiple JavaScript files you need to link, you can include multiple script elements with the appropriate src attributes:

<head>
  <!-- Other meta data goes here -->
  <script src="main.js" defer></script>
  <script src="second.js" defer></script>
  <script src="third.js" defer></script>
</head>

Exercises

Try recreating the code snippet from the tutorial and connect the main.js file to the index.html file.

References

The Script element on MDN

Back to: JavaScript Reference > JS Introduction