Home | SkillForge Blog | How To Run External JavaScript After the HTML Has Loaded

How To Run External JavaScript After the HTML Has Loaded

JavaScript, Web Design

When using JavaScript, sometimes you will run into errors because the external code being used is placed above the HTML it is calling/manipulating.  For this example, we have a HTML file that looks like this:

<!DOCTYPE html>
<meta charset=”utf-8″>
<title>Run JavaScript After HTML Loads</title>
<script src=”external.js”></script>
<div id=”changeMe”></div>

In that code we can see that it’s calling an external JavaScript file called external.js that has this code in it:

document.getElementById(“changeMe”).innerHTML = “I’ve been changed!”;

This is going out to the div with the id of changeMe and is going to switch out the text to say “I’ve been changed!” after the script runs.  The HTML runs line by line so be it goes out to the JavaScript file and tries to run it BEFORE it has loaded any of the HTML in the body tag.  Because of that, if we were to run this in Chrome we would get this error:

javascript error

This is telling us there’s an issue on the only line in the external.js file:

document.getElementById(“changeMe”).innerHTML = “I’ve been changed!”;

The external script is trying to select the div with the id of “changeMe” and change it’s innerHTML before it has been loaded in the browser so it errors out.  To fix that we use a magical attribute called “async” and we place it into our script tag like so:

<script src=”external.js” async></script>

The async attribute makes it so the script can be run separate (asynchronously) to the page loading and will wait for the HTML to load before it tries to run any of the scripts.  Before, it ran the external JavaScript first, then continued loading the page creating the error.  Now it makes it so the JavaScript can be run separate from the HTML and doesn’t have to load first.  This will eliminate the error we are getting.  After adding the async attribute we will get what we were expecting in the browser:

If you want to learn more, check out our JavaScript Training.  Have an amazing day!