Deferring JS Until Script Load

A common recommendation when using JavaScript is to put your <script> elements at the end of your HTML, including those that reference a JS file on your site. One issue, however, is that if you then have a script that references a function from another script, how do you ensure the other script is loaded already?

The problem

Let's say you have the following:

<script src="some/other/javascript.js"></script>
<script>
(function (){
        // call a function defined in the other JS file
})();
</script>

If javascript.js has not finished loading at the time you call a function defined in it, you'll get an error, and the function will never get called. This can be problematic if your site depends on it being called!

The solution

You can add a listener to that other script's "load" event, and then do your work in the listener. To make this work, you'll need to add an ID to the other script (I used "jsDependency" here, but use something that makes semantic sense).

<script id="jsDependency" src="some/other/javascript.js"></script>
<script>
(function (){
    document.querySelector('#jsDependency').addListener('load', function () {
        // call a function defined in the other JS file
    });
})();
</script>

As soon as the first script has finished loading, it will trigger any listeners on its "load" event, allowing the second script to execute correctly.