WEEK: 2
Active: January 31st - February 6th
Work Due: February 7th @ 8:00AM

JavaScript in HTML with the <script> Tag

Since this class is about incorporating JavaScript with web development we also need to learn how to place JS code into our HTML files. There are two primary ways of including JS code in HTML. However, they both utilize the same HTML tag, the script tag.

<script> </script>

Inline JavaScript

Inline JavaScript is JS code that has been written between the script tags, within the HTML file itself.

As an example, let’s take our first “Hello World!” program, and incorporate it into an HTML document. To do this, we will include a <script> element at the end of our HTML file.

NOTE: It is typically advised that developers include JavaScript tags at the end of an HTML file’s <body> element. This is to protect against slow connections. This way, a browser can load all content first, then load and execute any JavaScript code. That way, if the connection is slow, the user is not waiting on JS code before they can start viewing the webpage.

Our new file might look like the following;

[Code Download] [View on GitHub] [Live Example]


You should either;

  • download and open the above code, using the code download link below, in your own browser, open the console, and check the output.
  • or, open the code using the Live Example link, open the console, and check the output.

Regardless of which method you choose, you should see “Hello World!” printed to the console output, as in the image below, and like the previous example we wrote together. (Please note: the actual web browser window will be a blue blank screen.)

Example of 'Hello World!' in browser console

External JavaScript

We can also add JavaScript as separate files, that the main HTML document will link to. This has a few advantages and disadvantages.

  • advantages:
    • Allows for cleaner code, as we separate the JS code from the HTML content.
    • Can reduce load times if the JS files have been cached on the host computer.
  • disadvantages:
    • When first loading a page, additional linked files can increase load times.

To load external Javascript files, we will still use the script tag. However, instead of placing code between the tags, we will instead the file url, as a string to the tags src attribute. (i.e. <script src="url-to-file.js"></script> Notice, that we still include the closing tag.)

The above example would be created as follows, if using an external JS file.

[Code Download] [View on GitHub] [Live Example]


As with before, you should either;

  • download and open the above code, using the code download link below, in your own browser, open the console, and check the output.
  • or, open the code using the Live Example link, open the console, and check the output.

Regardless of which method you choose, you should see, yet again, “Hello World!” printed to the console output.


Previous section:
Next section: