Including JavaScript In Your Page

Including JavaScript in your page is a fairly simple process.

First, What Is JavaScript?

From the W3C Schools Site:

Including the JavaScript

You can include JavaScript in your HTML in two ways:

For the most part, you will include the JavaScript as an external file.

The script Tag

The script tag is what we use to include JavaScript on our site. It's a lot like the link tag you've already been using to include your CSS files.

Here's a very basic snippet of JavaScript using the script tag. This JavaScript is written directly into our HTML page. It will call an alert box as soon as the page loads.

<script>
  alert("This alert box was called with the onload event");
</script>

Slightly more useful, this will log a message to the Web Developer console:

<script>
  console.log("Logging a message for testing");
</script>

Using the script tag to include an external JavaScript file

To include an external JavaScript file, we can use the script tag with the attribute src. You've already used the src attribute when using images. The value for the src attribute should be the path to your JavaScript file.

<script src="path-to-javascript-file.js"></script>

The script tag should either be included between the <head> tags or just before the closing </body> tag in your HTML document.

JavaScript Files

JavaScript files are not HTML files or CSS files.

It's customary to put all JavaScript files in a folder called js.

Simple Demo of Including JavaScript

Here's a very simple demonstration of how to include an external JavaScript file into an HTML page.

Other People's JavaScript

For this class you are not expected to write any actual JavaScript code. Lucky for you, many people have already written lots of JavaScript and even allow you to use it for free.

JavaScript Libraries

A code library is usually a collection of code for a certain language. Generally, the library will abstract common and tedious programming tasks and make them easier and faster for designers and developers to write their code. Libraries don't generally do anything by themselves, they just provide an easier platform for people to build on.

Common JavaScript Libraries:

Of these libraries, jQuery is currently the most popular one. The others are not being as actively developed and are used much less often.

JavaScript File Sizes

Many JavaScript files can tend to be rather large, which can slow down the load time of your page. Popular frameworks usually offer a "minified" version of their code. You should always use the minified version in your pages because it will have a smaller file size and load faster.