How to load JavaScript

When learning something new we sometimes don’t know where to start. For JavaScript, what is the step before hello world? How do load JavaScript in the first place?

How to load JavaScript with the <script> tag

<script type="text/javascript" src="path/to/AwesomeJavaScript.js"></script>

Break loading JavasScript down:

<script> is the tag for loading scripts. You can load different types of scripts.

Because of different types of scripts, in HTML4 and earlier it is required to specify the type. In the case of JavaScript it is “text/javascript”.

But as of HTML5 the type attribute is not required and can be omitted.

The src attribute specifies the file. The path can be relative or absolute.

Relative paths are file paths from the point of view of the file loading it. If the HTML file is in /files/ and the JavaScript is at the root /, then the src would be src=”../file.js” for relative.

The absolute path, using the previous example, would be src=”/file.js”.

How to load a JavaScript file dynamically in JavaScript

// Create the script element
var script = document.createElement("script");
// Add type attribute
script.setAttribute("type", "text/javascript");
// Add the file path to the source attribute
script.setAttribute("src", "/path/to/awesomeJavaScript.js");

// Now it is time to load the file and at this point you'll see the file loaded in your network tab in the web development toolbar