JavaScript and HTML

JavaScript and HTML

including real programming code onto a webpage

·

2 min read

We can include Javascript in an HTML page in one of three ways:

JavaScript inline

In the early days or in very bad practices, once might see JavaScript placed inside HTML tags like this:

<a href="..." onClick="alert('hey')">Link</a>

where the value of the onClick attribute would contain Javascript!

JavaScript encapsulated

However, a more contained form of JavaScript would enter via a <script> tag in 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>

JavaScript from an external file

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

// app.js
const aVariable = true;

Then, we would load the file by placing an src attribute in the <script> tag instead:

<!-- index.html -->
<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; then, we could even add files from other sources like such:

<!-- index.html --> 

<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 reuse code more easily and keep the HTML structure clean and clear! Note two things:

  • the order of the <script> tags does matter:

    • if thirdpartycode2 depends on thirdpartycode1

      • thirdpartycode1 should appear higher up in the HTML
  • in older HTML we might see the optional type attribute which has become optional:

<script type="text/javascript" src="app.js"></script>

JavaScript deferred

If a <script>tag has to appear in the <head> tag, we can use the defer keyword:

  • this ensures that the rest of the HTML file gets loaded before the execution of this head script!
<html>

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

    <body>

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

    </body>

</html>