JavaScript in HTML

getting started with JavaScript on a webpage
// updated 2025-05-01 15:27

Much like in CSS, we can include JavaScript in an HTML page in one of three ways:

  • In-line script
  • <script> tag (in CSS, we used the <style> tag)
  • External script file (on a separate file with a .js extension)

In-line

As with CSS, we can place JavaScript inside the attribute values of HTML tags like this:

<a href="javascript:history.back()">Go back</a>

(This HTML would link to the last place that the user visited!)

Script tag

A more separated form of JavaScript would appear in a <script> tag within an HTML file:

<html>
  <head>
    <title>a page</title>
  </head>
  <body>
    <h1>a page</h1>
    <script>
      // our script here - this is a basic true/false variable: 
      const aVariable = true
    </script>
  </body>
</html>

Although this appears neater than in-line JavaScript, this still makes the code inside the <script> tag usable only in this specific HTML file. We could not use this code on other HTML pages.

External script file

Even better then, we could place JavaScript in a file like this:

/* app.js */
const aVariable = true

Then, we would load the file by placing it in a <script> tag:


<html>
    <head>
        <title>a page</title>
    </head>
    <body>
        <h1>a page</h1>
        <script src="app.js"></script>
    </body>
</html>

This makes for a more modular approach. We could then even add files from other sources like such:

<html>
    <head>
        <title>a page</title>
    </head>
    <body>
        <h1>a page</h1>
        <script src="thirdpartycode1/app.js"></script>
        <script src="thirdpartycode2/app.js"></script>
        <script src="app.js"></script>
    </body>
</html>

With this, we can re-use code more easily and reserve the HTML for page structure.

Note also:

  • the order of the <script> tags matter:
    • if thirdpartycode2 depends on thirdpartycode1
      • thirdpartycode1 should appear higher up in the HTML
  • in older HTML, the script tag might have the optional type attribute
    • this has become optional as browsers now can detect languages better

Deferred file

If a <script> tag somehow has to appear in the <head> tag of an HTML document, we can use the defer keyword. This will ensure that the rest of the HTML file gets loaded before the script's execution!

<html>

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

    <body>

        <!-- all the tags here get loaded before deferred.js takes effect -->

    </body>

</html>
⬅️ older (in textbook-javascript)
📒 JavaScript — an introduction
newer (in textbook-javascript) ➡️
JavaScript comments and whitespace 📒
⬅️ older (in code)
📒 JavaScript — an introduction
newer (in code) ➡️
JavaScript comments and whitespace 📒
⬅️ older (posts)
📒 JavaScript — an introduction
newer (posts) ➡️
JavaScript comments and whitespace 📒