How to execute a function when page has fully loaded?

How to execute a function when page has fully loaded?

I need to execute some JavaScript code when the page has fully loaded. This includes things like images.
I know you can check if the DOM is ready, but I don’t know if this is the same as when the page is fully loaded.


Solution 1:

That’s called onload. It came waaaaay before DOM ready was around, and DOM ready was actually created for the exact reason that onload waited on images.

window.onload = function () { alert("It's loaded!") }

Solution 2:

Usually you can use window.onload, but you may notice that recent browsers don’t fire window.onload when you use the back/forward history buttons.

Some people suggest weird contortions to work around this problem, but really if you just make a window.onunload handler (even one that doesn’t do anything), this caching behavior will be disabled in all browsers. The MDC documents this “feature” pretty well, but for some reason there are still people using setInterval and other weird hacks.

Related:  What does webpack mean by XX hidden modules

Some versions of Opera have a bug that can be worked around by adding the following somewhere in your page:

<script>history.navigationMode = 'compatible';</script>

If you’re just trying to get a javascript function called once per-view (and not necessarily after the DOM is finished loading), you can do something like this:

<img src="javascript:location.href='javascript:yourFunction();';">

For example, I use this trick to preload a very large file into the cache on a loading screen:

<img src="bigfile"

Solution 3:

For completeness sake, you might also want to bind it to DOMContentLoaded, which is now widely supported

document.addEventListener("DOMContentLoaded", function(event){
  // your code here

More info:

Solution 4:

Try this it Only Run After Entire Page Has Loaded

By Javascript

window.onload = function(){
    // code goes here

By Jquery

$(window).bind("load", function() {
    // code goes here

Solution 5:

the window.onload event will fire when everything is loaded, including images etc.

You would want to check the DOM ready status if you wanted your js code to execute as early as possible, but you still need to access DOM elements.

Related:  How to insert row in HTML table body in JavaScript

Solution 6:

Try this code

document.onreadystatechange = function () {
  if (document.readyState == "interactive") {

visit for more details