skip to content
Dev Journal

Linking JavaScript file

/ 2 min read

Last Updated:

When you write JavaScript, you should write them in a JavaScript file that ends with a .js extension. These JavaScript files can be named anything you want. Most people name their first JavaScript file either app.js or main.js

Then, to link a JavaScript file to HTML you should use <script> tag with the src attribute pointing to the JavaScript file. Place this tag before </body> tag.

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

Ensure the JavaScript file linked properly by adding this alert() function to your JavaScript file. if the link is correct, you’ll see a prompt when you open your index.html in a browser. Afterwards, remove this alert code.

main.js
alert('Your JavaScript is linked')

JavaScript Placement in HTML

It’s not recommended to add your JavaScript file within the <head> tag, as it can delay HTML and CSS display. if needed, use the async attribute.

<head>
<meta charset="utf-8"/>
<title>Title of website</title>
<script src="js/main.js"></script>
<script src="js/main.js" async></script>
</head>

Relative and Absolute Paths

Use a relative path to link your JavaScript file, starting with the file name or folder. Absolute paths start with a / or an HTTP protocol and are used for external resources like jQuery

<!--- Relative path -->
<script src="js/main.js"></script>
<!-- Absolute path-->
<script src="<HTTP protocol target to jquery file>"></script>