Tuesday, June 20th, 2006

Return of the document.onload problem

Category: Editorial

Dean Edwards worked on a document.onload solution back in the day. He has just updated it with new information that fixes the problem a lot cleaner in IE (no need for external files) all due to readyState outside of XHR:

javascript

  1. // for Internet Explorer (using conditional comments)
  2. /*@cc_on @*/
  3. /*@if (@_win32)
  4. document.write("<script id=__ie_onload defer src=javascript:void(0)>< \/script>");
  5. var script = document.getElementById("__ie_onload");
  6. script.onreadystatechange = function() {
  7.     if (this.readyState == "complete") {
  8.         init(); // call the onload handler
  9.     }
  10. };
  11. /*@end @*/

Add to this a fix for Safari:

javascript

  1. if (/WebKit/i.test(navigator.userAgent)) { // sniff
  2.     var _timer = setInterval(function() {
  3.         if (/loaded|complete/.test(document.readyState)) {
  4.             clearInterval(_timer);
  5.             delete _timer;
  6.             init(); // call the onload handler
  7.         }
  8.     }, 10);
  9. }

and Opera 9 supports DOMContentLoaded.

Posted by Dion Almaer at 1:59 am
8 Comments

+++--
3.7 rating from 69 votes

8 Comments »

Comments feed TrackBack URI

It’s worth clarifying something here – if the function implementing the IE fix is called at any point after load, which is not inconceivable, the entire page will vanish. document.onload calls only work while the page is still being parsed; at any other stage they are destructive in all browsers, and need to be carefully avoided.

Comment by henrah — June 20, 2006

… ^^argh.

by which I mean, such calls are destructive if they include document.write calls.

Also: Dion. Ben. Whoever. Can you please fix your comment system?

Comment by henrah — June 20, 2006

No, they can’t fix the comment system. If they could, it would have been done by now. Trust me, it’s been months.. they don’t care.

Comment by Ryan Gahl — June 20, 2006

Hello there, Ryan got me curious about the redirect error in the comment system… commenting just to “extract” some info. BTW anyone tried jsLINB? pages keeps disappearing (after some idle time )

Comment by Miguel Benevides — June 20, 2006

onLoad-Event Quärelen

Situation: Man hat sich für die werte Internetseite eine hübsche init-Funktion in JavaScript geschrieben und möchte diese nun ausführen, sobald die Seite geladen wird. Nun muss man nicht sehr erfahren sein, um hierbei zum document.onload Event de…

Trackback by Tonstube — June 20, 2006

I sort of like the blank screen when I comment, it makes me feel like I have a fresh start on the web, away from all those JS drop downs.
Calm blue ocean …

Comment by Dan — June 20, 2006

Thanks alot. very useful :)

Comment by Diviner — June 20, 2006

Interesting reading, thanks guys.

Comment by Jordan Windebank — June 20, 2006

Leave a comment

You must be logged in to post a comment.