Run JavaScript After DOM is Fully Loaded

Advertisement

Advertisement

Introduction

When writing JavaScript for a web browser, there are times when you want the page to fully load before the code is executed. This is particularly true if your JavaScript manipulates or utilized the HTML DOM. Your JavaScript will fail if it tries to reference an element that has not yet been loaded. This example will show you how to defer code from being executed until the web page has fully loaded.

Use DOMContentLoaded event callback

You can use the DOMContentLoaded event as the trigger for executing your code. Do this by using document.addEventListener() to tie a custom function to the event. This example shows you how to define a custom function that will execute only after the DOM is loaded. Note, while the DOM may be loaded, that does not necessarily mean every image and resource is completely done downloading.

document.addEventListener("DOMContentLoaded", function () {
  // Your code goes here
});

Using jQuery

The previous example uses "vanilla" JavaScript without any special framework. jQuery is a popular JavaScript framework that also has an easy way to defer code until the page is loaded.

// Be sure to include jquery library somewhere before this

$(document).ready(function() {
    // Your code goes here
});

Conclusion

After following this example you should understand how to write JavaScript code for the web browser that will not execute until the DOM is fully loaded.

References

Advertisement

Advertisement