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 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;
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.)
We can also add JavaScript as separate files, that the main HTML document will link to. This has a few advantages and disadvantages.
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;
Regardless of which method you choose, you should see, yet again, “Hello World!” printed to the console output.