1

I'm working without the JavaScript framework, but I want to call a function just when the DOM is loaded.

I can't/don't want to use the attribute onload on the <body> tag.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Christophe Debove
  • 6,088
  • 20
  • 73
  • 124
  • See http://stackoverflow.com/questions/732801/how-to-verify-if-a-webpage-is-completely-loaded-using-javascript – mamoo Nov 18 '11 at 10:40

3 Answers3

3

I think http://code.google.com/p/domready/ is exactly what you're looking for.

If you are ever writing your own JavaScript file that cannot depend on the existing libraries out there and would like to execute only after the page is loaded, this library is for you.

Simply do this:

<html lang="en">
<head>
        <script src="domready.js" type="application/javascript"></script>
        <script type="application/javascript">
                DomReady.ready(function() {
                    alert('dom is ready');
                });
        </script>
</head>
<body>

</body>
</html>
alessioalex
  • 62,577
  • 16
  • 155
  • 122
1

Well, I'm afraid cross-browser and DOM loaded don't go together easily. By recommendation is Ryan Morr's ondomready (https://github.com/ryanmorr/ondomready) but there are a ton of alterntives.

Graham
  • 6,484
  • 2
  • 35
  • 39
1

Here is the code:

  • in non-IE browsers, use DOMContentLoaded event
  • in IE top frame use scroll hack (see _readyIEtop)
  • in IE frame, simply use onload

    var onready = function(handler) {
        // window is loaded already - just run the handler
        if(document && document.readyState==="complete") return handler();
    
        // non-IE: DOMContentLoaded event
        if(window.addEventListener) window.addEventListener("DOMContentLoaded",handler,false);
    
        // IE top frame: use scroll hack
        else if(window.attachEvent && window==window.top) { if(_readyQueue.push(handler)==1) _readyIEtop(); }
    
        // IE frame: use onload
        else if(window.attachEvent) window.attachEvent("onload",handler);
    };
    
    // IE stuff
    var _readyQueue = [];
    var _readyIEtop = function() {
        try {
          document.documentElement.doScroll("left");
          var fn; while((fn=_readyQueue.shift())!=undefined) fn();
        }
        catch(err) { setTimeout(_readyIEtop,50); }
    };
    

jQuery tunes the IE a little more (lots of code), but in my tests it runs just before onload event anyway.

var test = function() { alert("ok"); }
onready(test);
Jan Turoň
  • 31,451
  • 23
  • 125
  • 169
  • I don't understand why you say me if none of these work, aren't you sure of your answer, in more you say mae use onload???? did you rode my question? – Christophe Debove Nov 18 '11 at 11:23
  • pardon my english: by "if none of these works" I mean "if it's not the case" - see the comments in my code. I have tested it here - http://jsfiddle.net/yCLZL/ – Jan Turoň Nov 18 '11 at 11:37