Run JavaScript code after page load using pure JS and jQuery
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.
|
1 2 3 |
window.onload = function() { alert('Page is loaded'); }; |
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.
|
1 2 3 |
window.addEventListener("load", function() { alert('Page is loaded'); }); |
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.
|
1 2 3 4 5 6 7 8 9 10 11 |
<html> <body onload="loaded();"></body> <script> function loaded() { alert('Page is loaded'); } </script> </html> |
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.
|
1 2 3 |
document.addEventListener("DOMContentLoaded", function() { alert('Page is loaded'); }); |
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)
|
1 2 3 |
$(document).ready(function() { alert('Page is loaded'); }); |
Alternatively, the $(handler) can be called, which is equivalent to the above syntax:
|
1 2 3 |
$(function() { alert('Page is loaded'); }); |
You can also watch for the load event on the window object using $(window).on("load", handler) method.
|
1 2 3 |
$(window).bind('load', function() { alert('Page is loaded'); }); |
That’s all about running JavaScript code after page load.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)