In this article, you'll learn how and where to include your JavaScript code.

HTML header

<html>
  <head>
    <title>Webpage</title>
    <script type="text/javascript">
      console.log("here");
    </script>
  </head>
  <body></body>
</html>

HTML body

<html>
  <head>
    <title>Webpage</title>
  </head>
  <body>
    <script type="text/javascript">
      console.log("here");
    </script>
  </body>
</html>

External File

Given a file named app.js, to include it in an HTML file named index.html:

<html>
  <head>
    <title>Webpage</title>
    <script src="app.js"></script>
  </head>
  <body></body>
</html>

ES6 - import & export

In the example below, we'll use 2 JavaScript files:

my-script.js

export function House() { 
  this.width = 100;
  this.length = 200;
}

second-script.js

function paint() { 
  ...
}
function clean() { 
  ...
}
export { paint, clean }

To include them both in an HTML file:

<html>
  <head>
    <title>Webpage</title>
    <script type="module">
      import { House } from "./my-script.js";
      import { paint, clean } from "./second-script.js";
      let house = new House();
    </script>
  </head>
  <body></body>
</html>

ES10 - dynamic import with async Early days Google Chrome only

my-script.js

export const helloEvent = () => {
  console.log('Hello World');
};

index.html

<html>
  <head>
    <title>Webpage</title>
    <script type="text/javascript">
      window.onload = function() {
        document.getElementById('helloButton').addEventListener("click", async() => {
          const module = await import('./myscript.js');
          module.helloEvent();
        });
      }
    </script>
  </head>
  <body></body>
</html>