Inspired by Dean Edwards, this function offers a more practical way to execute code as soon as the page has loaded – that is, the DOM content is ready for action, but images et al can still be loading. You will need addEvent.
It works best with recent versions of Firefox (or other Gecko browsers), Opera and Internet Explorer. I didn’t include the rather ugly Safari hack. There’s an onload fallback for Safari (see why) and miscellaneous exotic or obsolete browsers.
/**
* function whenDOMReady
* Copyright (C) 2006-2007 Dao Gottwald
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
* Contact information:
* Dao Gottwald <dao at design-noir.de>
*
* @version 1.3
* @url http://design-noir.de/webdev/JS/whenDOMReady/
*/
function whenDOMReady(fn) {
var f = arguments.callee;
if ("listeners" in f) { // already initialized
if (f.listeners) // still loading
f.listeners.push(fn);
else // DOM is ready
fn();
return;
}
f.listeners = [fn];
f.callback = function() {
removeEvent(window, "load", f.callback);
if (document.removeEventListener)
document.removeEventListener("DOMContentLoaded", f.callback, false);
if (f.listeners) {
while (f.listeners.length)
f.listeners.shift()();
f.listeners = null;
}
};
if (document.addEventListener)
document.addEventListener("DOMContentLoaded", f.callback, false);
/*@cc_on @if (@_win32) else
document.write("<script defer src=\"//:\""+
" onreadystatechange=\"if (this.readyState == 'complete')"+
" whenDOMReady.callback();\"><\/script>");
@end @*/
addEvent(window, "load", f.callback);
}
function init() {
// do fancy stuff with the document, like:
var links = document.getElementsByTagName('a');
// ...
}
whenDOMReady (init);
// we can enqueue multiple functions
whenDOMReady (function() {
var foo = document.getElementById('special-element');
// ...
});