How to start JavaScript in HTML

To start writing JavaScript in your HTML file, you’ll need to create <script> tags. Inside the tags you’ll write your JavaScript code.


<script>
    !(function() {
        const message = "hello world";
        console.log(message)
    })();
</script>

Where should you put <script> tags in the HTML markup?

The best play to insert your <script> tag is in the the head tag. This is because there are attributes such as the async & defer that will allow the browser to download the script but get executed differently.

Old practices would make you add them at the bottom of body tags because the browser would download them and execute them before DOM elements were even parsed.

With modern practices such as async & defer you can download the JavaScript code and execute it without blocking the parsing of the DOM.


<!-- Async -->
<script async></script>

<!-- Defer -->
<script defer></script>

async – This lets the browser know to download and execute the JavaScript code asynchronously. This is preferred if the code runs independent and doesn’t depend on any DOM elements.

defer – This lets the browser know to download synchronously with the rest of the HTML but to execute once the entire document has been loaded. This is preferred if you need to wait for the entire document to load.

I like to tweet about JavaScript and post helpful code snippets. Follow me there if you would like some too!