4 Ways To Run Javascript After Page Load – Simple Examples

Welcome to a quick tutorial on how to run Javascript after page load. Having some trouble with missing elements, variables, or functions? Want to delay a piece of Javascript until everything else is fully loaded?

The common ways to run Javascript after page load are:

  1. Add an event listener – document.addEventListener("load", FUNCTION);
  2. Add onload to the body tag – <body onload="FUNCTION()">
  3. Defer the script – <script src="SCRIPT.js" defer>
  4. Lastly, place the script at the very bottom of the page – Although this is not quite “after page load”.

That covers the basics, but let us walk through some detailed examples in this guide. Read on!

ⓘ I have included a zip file with all the example source code at the start of this tutorial, so you don’t have to copy-paste everything… Or if you just want to dive straight in.

 

 

REAL QUICK SLIDES

 

TABLE OF CONTENTS

Download & Notes Execute on Load Useful Bits & Links
The End

 

DOWNLOAD & NOTES

Firstly, here is the download link to the example code as promised.

 

EXAMPLE CODE DOWNLOAD

Click here to download the source code, I have released it under the MIT license, so feel free to build on top of it or use it in your own project.

 

QUICK NOTES

If you spot a bug, please feel free to comment below. I try to answer questions too, but it is one person versus the entire world… If you need answers urgently, please check out my list of websites to get help with programming.

 

 

EXECUTE ON PAGE LOAD

All right, let us now get into the ways and examples of how to run Javascript on page load.

 

1) EVENT LISTENER

1-event-listener.html
<!DOCTYPE html>
<html>
  <head>
    <title>Run Javascript On Page Load</title>
    <script>
    // (A) RUN THIS ON PAGE LOAD
    window.addEventListener("load", function(){
      document.getElementById("myTxt").style.color = "red";
    });
    </script>
  </head>
  <body>
    <!-- (B) HTML ELEMENTS -->
    <p id="myTxt">Hello world!</p>
  </body>
</html>

Events should be pretty self-explanatory, even if you have never heard of them before. They are fired whenever something of interest happens – Mouse click, scroll, keypress, video play, and more. In this example, we listen to the load event on the window itself; Run a piece of Javascript when the window is fully loaded.

P.S. You can also target the DOMContentLoaded event. The difference is that load is fired when everything is fully loaded. But DomContentLoaded is triggered as soon as all the HTML elements are ready. I.E. Images, CSS, videos may not be fully loaded.

 

2) BODY ON LOAD

2-onload.html
<!DOCTYPE html>
<html>
  <head>
    <title>Run Javascript On Page Load</title>
    <script>
    // (A) JAVASCRIPT FUNCTION
    function demo () {
      document.getElementById("myTxt").style.color = "green";
    }
    </script>
  </head>
 
  <!-- (B) RUN ON LOAD -->
  <body onload="demo();">
    <!-- (C) HTML ELEMENTS -->
    <p id="myTxt">Hello world!</p>
  </body>
</html>

Well, this kind of does the same thing as attaching addEventListener("load", FUNCTION). When the HTML document is loaded, onload="demo()" will be triggered.

 

 

3) DEFER SCRIPT LOAD

3a-defer.js
document.getElementById("myTxt").style.color = "blue";
3b-defer.html
<!DOCTYPE html>
<html>
  <head>
    <title>Run Javascript On Page Load</title>
    <!-- (A) DEFER SCRIPT LOAD -->
    <script src="3a-defer.js" defer></script>
  </head>
  <body>
    <!-- (B) HTML ELEMENTS -->
    <p id="myTxt">Hello world!</p>
  </body>
</html>

Yes, just add defer to the <script> tag, and it will hold until the entire page is done. For those who are confused about the difference between defer and onload:

  • defer will basically load the Javascript only when the HTML page is done.
  • onload does not mess with the loading order of the script… It simply runs the specified function when the page is ready.

P.S. Please take note that defer will not work with inline Javascript. I.E. Must load an external Javascript file.

 

4) SCRIPT AT BOTTOM (NOT QUITE AFTER PAGE LOAD)

4-bottom.html
<!DOCTYPE html>
<html>
  <head>
    <title>Run Javascript On Page Load</title>
  </head>
  <body>
    <!-- (A) HTML ELEMENTS -->
    <p id="myTxt">Hello world!</p>
 
    <!-- (B) SCRIPTS AT BOTTOM -->
    <script>
    document.getElementById("myTxt").style.color = "cyan";
    </script>
  </body>
</html>

Lastly, just put the scripts at the bottom of the page. This is not quite “after page load”, but it is… After everything else is nearly loaded.

 

 

USEFUL BITS & LINKS

That’s all for this guide, and here is a small section on some extras and links that may be useful to you.

 

WHICH IS THE BEST METHOD?

Personally, I will usually use window.addEventListener("DOMContentLoaded", FUNCTION) or defer loading non-critical scripts. But whichever makes the most sense for your own project is the best method.

 

INFOGRAPHIC CHEAT SHEET

Run Javascript After Page Load (Click To Enlarge)

 

EXTRA – HOW JAVASCRIPT LOADS

The above examples will serve well as a “quick fix”, but I do think it is better to not miss out on the fundamentals. Check out my other tutorial:

How Javascript Files Load (Normal vs Async vs Defer)

 

LINKS & REFERENCES

 

THE END

Thank you for reading, and we have come to the end of this guide. I hope that it has helped you with your project, and if you want to share anything with this guide, please feel free to comment below. Good luck and happy coding!

Leave a Comment

Your email address will not be published. Required fields are marked *