How to embed a JavaScript file in an HTML file

Let’s say you have a basic HTML document and you want to embed (import) an external JavaScript file into your document.

To do that you need to use the HTML <script> element:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=" />
    <title>Page title</title>
    <script src="main.js" defer></script>
  </head>
  <body>
    <h1>How to embed a JavaScript file in an HTML file</h1>
  </body>
</html>

Notice the defer attribute on the script element. Defer means that the code inside the main.js file won’t run until after the web page has finished loading all its content elements (text, images, links, etc.).

Obviously, that means that if for whatever reason you need to run your JavaScript file before all the webpage content is loaded, then you don’t use the defer attribute.

Note: the defer attribute only works when you embed external JavaScript files, not on inline JavaScript code.


Has this been helpful to you?

You can support my work by sharing this article with others, or perhaps buy me a cup of coffee 😊

Kofi

Share & Discuss on