<p>I know there are some ways to get notified when the page body has loaded (before all the images and 3rd party resources load which fires the <strong>window.onload</strong> event), but it's different for every browser.</p>

<p>Is there a definitive way to do this on all the browsers?</p>

<p>So far I know of:</p>

<ul>
<li><p><strong>DOMContentLoaded</strong> : On Mozilla, Opera 9 and newest WebKits. This involves adding a listener to the event:</p>

<p>document.addEventListener( "DOMContentLoaded", [init function], false );</p></li>
<li><p><strong>Deferred script</strong>: On IE, you can emit a SCRIPT tag with a @defer attribute, which will reliably only load after the closing of the BODY tag.</p></li>
<li><p><strong>Polling</strong>: On other browsers, you can keep polling, but is there even a standard thing to poll for, or do you need to do different things on each browser?</p></li>
</ul>

<p>I'd like to be able to go without using document.write or external files.</p>

<p>This can be done simply via jQuery:</p>

<pre><code>$(document).ready(function() { ... })
</code></pre>

<p>but, I'm writing a JS library and can't count on jQuery always being there.</p>

[{'answer_id': 65455, 'author': 'Sijin', 'author_id': 8884, 'author_profile': 'https://Stackoverflow.com/users/8884', 'pm_score': 1, 'selected': False, 'text': '<p>Just take the relevant piece of code from jQuery, John Resig has covered most of the bases on this issue already in jQuery.</p>\n'}, {'answer_id': 65476, 'author': 'Dave Ward', 'author_id': 60, 'author_profile': 'https://Stackoverflow.com/users/60', 'pm_score': -1, 'selected': False, 'text': '<p>This works pretty well:</p>\n\n<pre><code>setTimeout(MyInitFunction, 0);\n</code></pre>\n'}, {'answer_id': 65527, 'author': 'John Millikin', 'author_id': 3560, 'author_profile': 'https://Stackoverflow.com/users/3560', 'pm_score': 4, 'selected': True, 'text': "<p>There's no cross-browser method for checking when the DOM is ready -- this is why libraries like jQuery exist, to abstract away nasty little bits of incompatibility.</p>\n\n<p>Mozilla, Opera, and modern WebKit support the <code>DOMContentLoaded</code> event. IE and Safari need weird hacks like scrolling the window or checking stylesheets. The gory details are contained in jQuery's <code>bindReady()</code> function.</p>\n"}, {'answer_id': 65582, 'author': 'Michael Cramer', 'author_id': 1496728, 'author_profile': 'https://Stackoverflow.com/users/1496728', 'pm_score': 2, 'selected': False, 'text': '<p>YUI uses three tests to do this: for Firefox and recent WebKit there\'s a DOMContentLoaded event that is fired. For older Safari the document.readyState watched until it becomes "loaded" or "complete". For IE an HTML &lt;P&gt; tag is created and the "doScroll()" method called which should error out if the DOM is not ready. The source for <a href="http://developer.yahoo.com/yui/docs/Event.js.html" rel="nofollow noreferrer">YAHOO.util.Event</a> shows YUI-specific code. Search for "doScroll" in the Event.js.</p>\n'}, {'answer_id': 66209, 'author': 'Pat', 'author_id': 238, 'author_profile': 'https://Stackoverflow.com/users/238', 'pm_score': 2, 'selected': False, 'text': "<p>Using a library like jQuery will save you countless hours of browsers inconsistencies.</p>\n\n<p>In this case with jQuery you can just</p>\n\n<pre><code>$(document).ready ( function () {\n    //your code here\n});\n</code></pre>\n\n<p>If you are curious you can take a look at the source to see how it is done, but is this day and age I don't think anyone should be reinventing this wheel when the library writer have done all the painful work for you.</p>\n"}, {'answer_id': 67157, 'author': 'levik', 'author_id': 4465, 'author_profile': 'https://Stackoverflow.com/users/4465', 'pm_score': 2, 'selected': False, 'text': '<p>I found this page, which shows a compact self-contained solution. It seems to work on every browser and has an explanation on how:</p>\n\n<p><a href="http://www.kryogenix.org/days/2007/09/26/shortloaded" rel="nofollow noreferrer">http://www.kryogenix.org/days/2007/09/26/shortloaded</a></p>\n'}, {'answer_id': 70595, 'author': 'hulver', 'author_id': 11496, 'author_profile': 'https://Stackoverflow.com/users/11496', 'pm_score': -1, 'selected': False, 'text': '<p>Using setTimeout can work quite well, although when it\'s executed is up to the browser. If you pass zero as the timeout time, the browser will execute when things are "settled".</p>\n\n<p>The good thing about this is that you can have many of them, and don\'t have to worry about chaining onLoad events.</p>\n\n<pre><code>setTimeout(myFunction, 0);\nsetTimeout(anotherFunction, 0);\nsetTimeout(function(){ doSomething ...}, 0);\n</code></pre>\n\n<p>etc.</p>\n\n<p>They will all run when the document has finished loading, or if you set one up after the document is loaded, they will run after your script has finished running.</p>\n\n<p>The order they run in is not determined, and can change between browsers. So you can\'t count on <code>myFunction</code> being run before <code>anotherFunction</code> for example.</p>\n'}, {'answer_id': 71085, 'author': 'Slartibartfast', 'author_id': 4433, 'author_profile': 'https://Stackoverflow.com/users/4433', 'pm_score': 0, 'selected': False, 'text': '<p>Why not this:  </p>\n\n<pre><code>&lt;body&gt;  \n  &lt;!-- various content --&gt;  \n  &lt;script type="text/javascript"&gt;  \n  &lt;!--  \n    myInit();  \n  --&gt;\n  &lt;/script&gt;  \n&lt;/body&gt;  \n</code></pre>\n\n<p>If I understand things correctly, myInit is gonna get executed as soon as browser hit it in the page, which is last thing in a body.</p>\n'}, {'answer_id': 15338341, 'author': 'Justus Romijn', 'author_id': 334243, 'author_profile': 'https://Stackoverflow.com/users/334243', 'pm_score': 0, 'selected': False, 'text': '<p>The fancy crossbrowser solution you are looking for....doesn\'t exist... (imagine the sound of a big crowd saying \'aahhhh....\').</p>\n\n<p><strong>DomContentLoaded</strong> is simply your best shot. You still need the <code>polling</code> technique for IE-oldies.</p>\n\n<ol>\n<li>Try to use addEventListener;</li>\n<li>If not available (IE obviously), check for frames;</li>\n<li>If not a frame, scroll until no error get\'s thrown (polling);</li>\n<li>If a frame, use IE event document.onreadystatechange;</li>\n<li>For other non-supportive browsers, use old document.onload event.</li>\n</ol>\n\n<p>I\'ve found the following code sample on <a href="http://javascript.info/tutorial/onload-ondomcontentloaded#the-crossbrowser-domcontentloaded-handling-code" rel="nofollow">javascript.info</a> which you can use to cover all browsers:</p>\n\n<pre><code>function bindReady(handler){\n\n    var called = false\n\n    function ready() { \n        if (called) return\n        called = true\n        handler()\n    }\n\n    if ( document.addEventListener ) { // native event\n        document.addEventListener( "DOMContentLoaded", ready, false )\n    } else if ( document.attachEvent ) {  // IE\n\n        try {\n            var isFrame = window.frameElement != null\n        } catch(e) {}\n\n        // IE, the document is not inside a frame\n        if ( document.documentElement.doScroll &amp;&amp; !isFrame ) {\n            function tryScroll(){\n                if (called) return\n                try {\n                    document.documentElement.doScroll("left")\n                    ready()\n                } catch(e) {\n                    setTimeout(tryScroll, 10)\n                }\n            }\n            tryScroll()\n        }\n\n        // IE, the document is inside a frame\n        document.attachEvent("onreadystatechange", function(){\n            if ( document.readyState === "complete" ) {\n                ready()\n            }\n        })\n    }\n\n    // Old browsers\n    if (window.addEventListener)\n        window.addEventListener(\'load\', ready, false)\n    else if (window.attachEvent)\n        window.attachEvent(\'onload\', ready)\n    else {\n        var fn = window.onload // very old browser, copy old onload\n        window.onload = function() { // replace by new onload and call the old one\n            fn &amp;&amp; fn()\n            ready()\n        }\n    }\n}\n</code></pre>\n'}]
['https://Stackoverflow.com/questions/65434', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4465/']