2

I write document.onload code inside my head tag.. but it doesn't seems to work. here is my code..

<head>
<script>
    document.onload = function () {
        alert("Window Loaded...!!");
    }
</script>
</head>

But if i replace with window.onload it perfectly works!! What is the problem? Am I doing something wrong ??

Uthaiah
  • 1,283
  • 13
  • 14
  • 1
    What browser (and version of browser) do you use? I think that some do not support the `document.onload` function. Check these answers for a bit more information about the diff between `document.onload` and `window.onload`: http://stackoverflow.com/a/588048/1980359 - http://stackoverflow.com/a/7371558/1980359 – Jite Jun 02 '14 at 07:38
  • I use Chrome, Version 35.0.1916.114 m – Uthaiah Jun 02 '14 at 07:43
  • I have never heard about `document.onload`. I guess the problem is that `document.onload` is not a valid property of Document elements (it just doesn't exist). – Felix Kling Jun 02 '14 at 07:50
  • Chrome does not support `document.onload`. – Jite Jun 02 '14 at 07:51
  • It supports.. See this link.. http://goo.gl/G1Yasu I have shared my bowser console screenshot – Uthaiah Jun 02 '14 at 07:55
  • 1
    Every resource i can find on the net says that chrome (or most of the major browsers) does not support it, or don't mention the event at all, except your screenshot. Your code does not work, which also indicates that **it is not supported**. If you are 100% certain that it still is supported, keep using the code you provided, cause if it is, it should work. – Jite Jun 02 '14 at 08:06

1 Answers1

10

As far as I'm aware, the closest you can come to your method is:

document.addEventListener('DOMContentLoaded', function () {
   /* your logic here */
});

The problem you have is document may not have a method of onload for a particular browser. Luckily! The window does in most cases. :) Give that a try for your JavaScript invocation.

lindsay
  • 972
  • 2
  • 11
  • 21
  • No I dont agree.. each and every element in the DOM will have all the events. I am using Visual studio.. and it shows me onload for document also. – Uthaiah Jun 02 '14 at 07:41
  • Good idea... It worked!! but tell me why it doesn't work when i directly add document.onload?? – Uthaiah Jun 02 '14 at 07:42
  • Are you sure? I've tried something like "document.body.getElementById()" and it hasn't worked; yet "document.getElementById" has. – lindsay Jun 02 '14 at 07:44
  • @Uthaiah the answer below gave a great example. Pretty much said everything I might have :-) – lindsay Jun 02 '14 at 07:46
  • 1
    document.body has only three DOM access functions document.body.getElementsByClassName(),getElementsByTagName() and getElementsByTagNameNS() – Uthaiah Jun 02 '14 at 07:51
  • 1
    also note that `window.onload` is triggered only after all external resources including images and scripts are loaded. – sabithpocker Jun 02 '14 at 07:52