Skip to content
blog
2 min read

Linking JavaScript file

Learn how to link JavaScript files to HTML, including naming practices, correct use of the script tag, and the differences between relative and absolute paths.

To use JavaScript on a web page, you link an external .js file to your HTML using a <script> tag.

The script Tag

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

Place it at the end of <body>, just before the closing tag:

<!DOCTYPE html>
<html>
<head>
<title>My Page</title>
</head>
<body>
<h1>Hello</h1>
<script src="app.js"></script>
</body>
</html>

Why at the end? The browser reads HTML top to bottom. If the script is in <head>, it runs before the page elements exist — and your JavaScript can’t find elements that haven’t been created yet.

defer and async

Alternatively, use defer in <head> to load the script without blocking and run it after the page is parsed:

<head>
<script src="app.js" defer></script>
</head>

defer is the modern approach and works well in most cases. async is similar but runs as soon as the download finishes, without waiting for the full page — use it for independent scripts like analytics.

File Naming

  • Lowercase, no spaces: app.js, main.js, utils.js
  • Use hyphens for multi-word names: form-handler.js, nav-menu.js
  • Keep it descriptive but short

Relative vs. Absolute Paths

A relative path starts from the HTML file’s location:

<script src="js/app.js"></script>
<!-- file is in a js/ folder -->
<script src="../shared/utils.js"></script>
<!-- one folder up -->

An absolute path starts from the domain root:

<script src="/assets/js/app.js"></script>

For local projects, relative paths are simpler. For deployed sites, absolute paths avoid issues when moving files around.