0

I am trying some hands on with javascript core concepts and came across this interesting thought. When I use the native javascript and try executing some events on the document load as below I get an error:

document.addEventListener('load',function(){ //this doesn't alert doesn't get fired
alert("document load event listener fired!");
});

But if I change the above code as below it works:

window.addEventListener('load',function(){//this works alert gets fired
alert("Window load event listener fired!");
});

A possible explanation that comes to my mind is that the window the parent object in browser object model is loaded the first before anything else can be ready or accessed.

However in jQuery (something I have been more comfortable with) the syntax clearly starts with document as below:

$(document).ready(function() {
    // some code here
});

I guess jQuery has an inbuilt wrapper around $(document) which actually takes care of firing the window load event before any further code mentioned inside it can be executed.

Is my understanding correct?

raikumardipak
  • 1,461
  • 2
  • 29
  • 49
  • Possible duplicate of [window.onload vs $(document).ready()](http://stackoverflow.com/questions/3698200/window-onload-vs-document-ready) – Hodrobond Jan 13 '17 at 05:17
  • can you create a scenario where you think the first with document load is not working? seems okay to me and it works. – Jai Jan 13 '17 at 05:19
  • `get an error in console` what is the error? - that code fragment is completely error free (perhaps the goal is incorrect, but the code will NOT produce an error as is) - unless you meant that the code inside the handler is giving you the error - without the code, who knows – Jaromanda X Jan 13 '17 at 05:20
  • @JaromandaX : Sorry Jaromanda, there is indeed no error log in console but the code after doesn't get executed , int htis case the alert doesn't get executed. Updated the code and the question. meanwhile I am looking at the other suggested question too – raikumardipak Jan 13 '17 at 05:29
  • @Jai updated the code template to share the exact scenario i m facing. The code after the document.addEventListener (the alert statement doesn't get executed) – raikumardipak Jan 13 '17 at 05:29
  • 1
    yeah that would be because document doesn't emit a load event – Jaromanda X Jan 13 '17 at 05:35

0 Answers0