How To Link Javascript to HTML Using the Src Attribute

How To Link Javascript to HTML Using the Src Attribute

·

1 min read

To link a JavaScript file to an HTML document, you need to use the <script> tag.

The Src Attribute

The src attribute allows you to point to a URL that has an external script file.

<script src="js/script.js"></script> — this points to a file called 'script.js' inside the folder 'js'.

You can also point it to an external absolute URL:

<script src="https://example.com/js/script.js"></script>

Where to place your script tag

You can place the script tag in:

  1. In between the <head> tags.
  2. Before the closing </body> tag.
  3. Both.
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width">
  <title>Codewell - Free Frontend Coding Challenges</title>

<script src="/javascript/script.js"></script>
</head>


<body>
  <!-- Content --> 
  <script src="/javascript/script.js"></script>
</body>
</html>

There are cases where you would want to place it in the <head> tag, and cases where you would want to place it at the bottom of the <body> tag. This article goes more in detail about it.

If you're just learning Javascript, read our blog on websites you can use to practice your skills here.