[javascript] How to make JavaScript execute after page load?

Comparison

In below snippet I collect choosen methods and show their sequence. Remarks

  • the document.onload (X) is not supported by any modern browser (event is never fired)
  • if you use <body onload="bodyOnLoad()"> (F) and at the same time window.onload (E) then only first one will be executed (because it override second one)
  • event handler given in <body onload="..."> (F) is wrapped by additional onload function
  • document.onreadystatechange (D) not override document .addEventListener('readystatechange'...) (C) probably cecasue onXYZevent-like methods are independent than addEventListener queues (which allows add multiple listeners). Probably nothing happens between execution this two handlers.
  • all scripts write their timestamp in console - but scripts which also have access to div write their timestamps also in body (click "Full Page" link after script execution to see it).
  • solutions readystatechange (C,D) are executed multiple times by browser but for different document states:
    • loading - the document is loading (no fired in snippet)
    • interactive - the document is parsed, fired before DOMContentLoaded
    • complete - the document and resources are loaded, fired before body/window onload

_x000D_
_x000D_
<html>_x000D_
_x000D_
<head>_x000D_
  <script>_x000D_
    // solution A_x000D_
    console.log(`[timestamp: ${Date.now()}] A: Head script`);_x000D_
    _x000D_
    // solution B_x000D_
    document.addEventListener("DOMContentLoaded", () => {_x000D_
      print(`[timestamp: ${Date.now()}] B: DOMContentLoaded`);_x000D_
    });_x000D_
_x000D_
    // solution C_x000D_
    document.addEventListener('readystatechange', () => {_x000D_
      print(`[timestamp: ${Date.now()}] C: ReadyState: ${document.readyState}`);_x000D_
    });_x000D_
   _x000D_
    // solution D_x000D_
    document.onreadystatechange = s=> {print(`[timestamp: ${Date.now()}] D: document.onreadystatechange ReadyState: ${document.readyState}`)};_x000D_
    _x000D_
    // solution E (never executed)_x000D_
    window.onload = () => {_x000D_
      print(`E: <body onload="..."> override this handler`);_x000D_
    };_x000D_
_x000D_
    // solution F_x000D_
    function bodyOnLoad() {_x000D_
      print(`[timestamp: ${Date.now()}] F: <body onload='...'>`);      _x000D_
      infoAboutOnLoad(); // additional info_x000D_
    }_x000D_
    _x000D_
    // solution X_x000D_
    document.onload = () => {print(`document.onload is never fired`)};_x000D_
_x000D_
_x000D_
_x000D_
    // HELPERS_x000D_
_x000D_
    function print(txt) { _x000D_
      console.log(txt);_x000D_
      if(mydiv) mydiv.innerHTML += txt.replace('<','&lt;').replace('>','&gt;') + '<br>';_x000D_
    }_x000D_
    _x000D_
    function infoAboutOnLoad() {_x000D_
      console.log("window.onload (after  override):", (''+document.body.onload).replace(/\s+/g,' '));_x000D_
      console.log(`body.onload==window.onload --> ${document.body.onload==window.onload}`);_x000D_
    }_x000D_
            _x000D_
    console.log("window.onload (before override):", (''+document.body.onload).replace(/\s+/g,' '));_x000D_
_x000D_
  </script>_x000D_
</head>_x000D_
_x000D_
<body onload="bodyOnLoad()">_x000D_
  <div id="mydiv"></div>_x000D_
_x000D_
  <!-- this script must te at the bottom of <body> -->_x000D_
  <script>_x000D_
    // solution G_x000D_
    print(`[timestamp: ${Date.now()}] G: <body> bottom script`);_x000D_
  </script>_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
_x000D_
_x000D_

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to html

Embed ruby within URL : Middleman Blog Please help me convert this script to a simple image slider Generating a list of pages (not posts) without the index file Why there is this "clear" class before footer? Is it possible to change the content HTML5 alert messages? Getting all files in directory with ajax DevTools failed to load SourceMap: Could not load content for chrome-extension How to set width of mat-table column in angular? How to open a link in new tab using angular? ERROR Error: Uncaught (in promise), Cannot match any routes. URL Segment

Examples related to dom

How do you set the document title in React? How to find if element with specific id exists or not Cannot read property 'style' of undefined -- Uncaught Type Error adding text to an existing text element in javascript via DOM Violation Long running JavaScript task took xx ms How to get `DOM Element` in Angular 2? Angular2, what is the correct way to disable an anchor element? React.js: How to append a component on click? Detect click outside React component DOM element to corresponding vue.js component

Examples related to dom-events

Detecting real time window size changes in Angular 4 Does Enter key trigger a click event? What are passive event listeners? Stop mouse event propagation React onClick function fires on render How do you Hover in ReactJS? - onMouseLeave not registered during fast hover over iFrame onload JavaScript event addEventListener, "change" and option selection Automatically pass $event with ng-click? JavaScript click event listener on class

Examples related to pageload

Auto-click button element on page load using jQuery Force page scroll position to top at page refresh in HTML How to make JavaScript execute after page load? $(document).ready equivalent without jQuery How to display a loading screen while site content loads Is there a cross-browser onload event when clicking the back button?