HTML

<div id=“hello-world”></div>

<script>

document.getElementById(“hello-world”).innerHTML = “Hello World!”;

</script>

You are now looking at your first snippet of JavaScript. We won’t break down the syntax just yet, but we will analyse what is going on here. You’ll notice we have added a set of <script> tags to wrap around our JavaScript. This is the most basic way of getting JavaScript to run on your page. The <script> tag tells the browser that we are trying to execute JavaScript code and to process it as JavaScript. In this example, if you were to save the code as a.html file and open it in the browser, the page would show Hello World! as if the text had been entered into the div all along – however, this isn’t the case.

JavaScript runs when you open the webpage, so for a short amount of time the ‘hello-world’ div would have been completely empty, until the browser reached the JavaScript code, which it executed and carried out its request of placing the Hello World! text into the ‘hello-world’ div.

This is only a basic example. JavaScript can do a lot more than simply insert text into a div. Let’s continue on our journey to master the basics of JavaScript.

Executing JavaScript

As we have seen above, JavaScript runs nicely when entered directly into your webpage. When placing your <script> tag you typically place it either inside the body tag or inside the head tag. It is generally considered best practice to place your script tags at the bottom of the body element as this improves the page loading speed. When the browser hits a snippet of JavaScript, it has to process it, which slows down the display speed of the page. Therefore, if we place our script tags at the bottom, the browser can go through and render all of the elements, then run the scripts at the end. This way the user will see the page render quicker than if the script tags were placed in the middle of the HTML tags.

Using the <script> tags is a nice and easy way of getting your code to execute, but it’s not the only way. Using script tags can get quite messy, especially if we have a lot of JavaScript code to run. Your HTML page can end up getting very long and confusing, not to mention difficult to navigate if you include all of your script directly on the page. Like with CSS, this is where using external files comes into practice. As with CSS we can create a separate file (in this case with a.js file extension), which we can point a reference to and our webpage will then find and include the file for us, just like we do with our external stylesheets.

Scripts are loaded using the following snippet: