views:

823

answers:

4

From external JS script I use document.readystate to determine whether the document is loaded.

If its not loaded I attach Onload event listner.

However when I run the script from IEPRO (similar to FF greasemonkey) on IE7 document.readystate returns 'undefined'. (I guess that IE7PRO runs the script after the document has loaded already).

How can I tell if the document is loaded or not in other ways that will work across browsers?

Clarifications (following first two answers): 1.My question is not how to perform onload attaching. My question is how to determine whether the document (or DOM) has already loaded in other means than document.readystate

  1. I cant change the document. my script is an addon to random pages I have no control of.
+1  A: 

The only cross-browser way of doing this, that I know of, is to attach a function to the load event of window; this script should probably go in the head. When this fires, set a boolean so that you know everything is loaded later.

The Prototype library does this; see function fireContentLoadedEvent() in the source.

geowa4
+1  A: 

You can do this in body.onload:

<body onload="document.ready=true;">...

This JavaScript will be executed after the document has been loaded. Just wait until document.ready is true (or no longer underfined).

The better way is to call a JS function in onload which then invokes your external script. This doesn't involve busy waiting but mmigth not work in your case. If you load the external document in a frame, you can store the function to call in the parent document and use "window.parent.function()" from the nested document.

Aaron Digulla
+1  A: 

I am not sure of your whole conclusion but sounds like you can just use jquery and set up your code like this:

  <script language="javascript" type="text/javascript">

    $(document).ready(function(){
 //have all your code of what you are trying to do here
 //
//
  });
</script>
TStamper
+1  A: 

The help site for IEPRO UserScripts seems to indicate they run after the page is loaded. So why do you need to check if the page is loaded?

Will Rickards