First JavaScript

This first example of JavaScript demonstrates how we attach JavaScript into a web page so that the script can interact with the page. It is traditional with programming languages to start with a program that displays "hello world" so we will do the same.

For the basic examples and also a number of the more advanced ones the example shows both the HTML and the JavaScript as two separate textareas. You should save the JavaScript in a file with the name referenced in the src="" attribute of the script tag in order to link the two together.

This example may look different from other JavaScript examples you may have seen because JavaScript has changed somewhat over the years both in what it can do and also in how we would normally use it. One difference between modern JavaScript and JavaScript the way that it used to be coded is that the modern ideal is to keep the JavaScript completely separated from the HTML. Only the script tag just before the end of the HTML links the two together.

To keep things simple for this first example we will identify the part of the body of our web page that we wish to update by adding an id to that tag. The JavaScript can then use the id to access and update the content of our web page. Examples in the DOM series will demonstrate other ways to access the part of the web page to be updated.

The first and last lines of the code wrap the JavaScript in its own scope so that the code is completely independent of any other scripts you add to the page. The second line tells the browser that you are using the post 2009 version of JavaScript rather than the pre 2009 version. These will be explained in more detail later in this basics series.

Currently it is considered best to place the script tag immediately prior to the closing body tag as this means that everything else in the web page is already loaded before the JavaScript runs. This both makes it quicker for the rest of the page to load into the browser and also means that we know that the content we want to update is already there to be updated once the script starts.

Note that to support Internet Explorer 8 and earlier you need to specify type="text/javaScript" instead of the correct JavaScript MIME type of "application/javascript".


This site is © copyright Stephen Chapman - Felgall Pty Ltd 2011-2016.

Privacy Policy | Terms and Conditions

You are welcome to use any the example JavaScript from this site in the scripts for your site or any that you develop for others but may not use the longer example scripts that contain a copyright notice in any other way without permission.