This post will discuss how to run JavaScript code after page load using pure JS and jQuery.

JavaScript and jQuery library offers several ways to execute a method after the DOM is ready. This post provides a detailed overview of methods to accomplish this.

1. Using JavaScript

In pure JavaScript, the standard method to detect a fully loaded page is using the onload event handler property. The load event indicates that all assets on the webpage have been loaded. This can be called with the window.onload in JavaScript.

Edit in JSFiddle

 
The following code uses addEventListener() method to listen for the load event to detect a fully loaded page. This is equivalent to the above code.

Edit in JSFiddle

 
Although not recommended, you can also call a JavaScript method on page load using HTML <body> tag. The idea is to use the onload attribute in the body tag.

Edit in JSFiddle

 
Note that the DOMContentLoaded event would be more appropriate if you just need your code to run when the DOM is fully loaded, without waiting for stylesheets and images to finish loading.

Edit in JSFiddle

2. Using jQuery

With jQuery, you can run JavaScript code as soon as the DOM is fully loaded using the .ready() method, which is equivalent to window.onload in JavaScript. Any of the following syntaxes can be used, which are all the same:

  • $(document).ready(handler)
  • $("document").ready(handler)
  • $().ready(handler)

Edit in JSFiddle

 
Alternatively, the $(handler) can be called, which is equivalent to the above syntax:

Edit in JSFiddle

 
You can also watch for the load event on the window object using $(window).on("load", handler) method.

Edit in JSFiddle

That’s all about running JavaScript code after page load.