0

I have an index.html file which includes a javascript file. Javascript file has a document.onload function which never gets executed. Can someone tell me why is this not being executed when DOM is loaded.

console.log("javascript file started loading");
document.onload = function () {
  console.log("document loaded");
  alert("DOM is ready");
}
<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title></title>
  </head>
  <body>
    <script src="app.js"></script>
    <h1>cool page onload</h1>
  </body>
</html>
user3807454
  • 39
  • 1
  • 6
  • 1
    @Xufox my question is when will document.onload function be executed . If it will not be executed then what is the use of this function? – user3807454 Feb 04 '18 at 08:26
  • 1
    The accepted answer of the dup answers that question too: "_... the browser will not do anything special with it._". It's just a custom function like `foo()`. – Teemu Feb 04 '18 at 08:29

2 Answers2

0

onload in window,not document

window.onload = function () {
  console.log("document loaded");
  alert("DOM is ready");
}

if you want to use document,

document.addEventListener("DOMContentLoaded", function(event) {
    console.log("document loaded");
    alert("DOM is ready");
});
xianshenglu
  • 4,009
  • 1
  • 10
  • 25
  • window.onload function will be executed when the DOM, css files, images and everything is loaded. I want the document.onload function to be executed when the dom is loaded – user3807454 Feb 04 '18 at 07:57
  • already suggested here https://stackoverflow.com/questions/799981/document-ready-equivalent-without-jquery – sbp Feb 04 '18 at 07:58
  • @user3807454,so you can use DOMContentLoaded,see my answer – xianshenglu Feb 04 '18 at 07:58
-2

The function document works if you apply jQuery to your website. Also make sure that your script tag is before the closing body tag so that the DOM can load.