views:

195

answers:

2

I have a script that will be inserted into an unknown page at an unknown time. Is it possible to tell from this script if window.onload has fired yet?

I have no control over the host page. I can't add any markup or scripts to it. All I know is that my script will be inserted into the page at some point. It could be before window.onload or after; and I need to detect which side of that event I'm on.

+1  A: 

jQuery's ready() will queue a function to be fired when the document is loaded, or fire immediately if the document is already loaded:

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

Just be sure jQuery is included before your script block. If you can't include any script resources directly, you can always copy the body of jQuery-min in your script itself.

Rex M
jQuery as of 1.3.2 cannot detect if the document is loaded if it is itself included after the document has loaded (e.g. bookmarklet, dynamic <script> inclusion, etc), in *non*-IE browsers. In such cases the function passed to `.ready()` will never be called. I'm not sure if the OP is inquiring about such a use-case but just thought I'd mention it.
Crescent Fresh
jQuery's ready function doesn't appear to work unless it is loaded before window.onload.
DietCoke
@Diet: in IE it works, as I mentioned. Anyway I take it from your comment that the code you are writing needs to work if included via a dynamic `<script>` tag injected into the DOM? Please clarify.
Crescent Fresh
yeah, it needs to work via dynamic script injection...
DietCoke
OK so here's the bug report for what I described: http://dev.jquery.com/ticket/4196 Nothing has happened with it for 8 months :(
Crescent Fresh
+1  A: 

Updated Answer: Look at this site. He uses a trick by seeing if the last element of document.getElementsByTagName("*") is defined or not. It seems to work in Opera and IE.


Original Answer: You can't check, but you can do:

window.setTimeout(function () {
    // do your stuff
}, 0);

That will do your stuff definitely after the page has loaded.

Anthony Mills
That will run the function before the DOM is ready in Opera, and may error out in IE. See http://remysharp.com/demo/onload.php for the IE problem.
Crescent Fresh
I've updated my answer with new information found today.
Anthony Mills
Nice find. I want to run that solution through the laundry, see how well it works.
Crescent Fresh