8

Can someone point me in the direction to hook the DOM loaded event?

Basically, i want to display a loader while the dom is loading (I dont mean Ajax requests- the first time a user hits a page) ?

Thanks all in advance

Orry
  • 2,578
  • 2
  • 18
  • 14

4 Answers4

31

If you're not using a framework, use the DOMContentLoaded event:

document.addEventListener('DOMContentLoaded', function() {
  // ...
})
Elliot Winkler
  • 2,336
  • 20
  • 17
  • 1
    Great! Mozilla has a nice doc on this: https://developer.mozilla.org/en/DOM/DOM_event_reference/DOMContentLoaded – philo Jun 26 '12 at 22:44
10

All of the popular Javascript libraries have a "DOM loaded" event you can use for this.

Essentially:

<html>
<head>
    <script>
    // if using jQuery
    $(document).ready(function() { $('#loading').hide(); });
    // if using Prototype
    document.observe("dom:loaded", function() { $('loading').hide(); });
    </script>
</head>
<body>
    <div id="loading">Loading...</div>
    <!-- rest of page -->
</body>
</html>
Paolo Bergantino
  • 480,997
  • 81
  • 517
  • 436
0

The proper way to do this without a library (and really, even with a library, since you're dealing with script blocking and IE unpredictability) is to put a script at the very end of the page:

onLoaded = function(){ ... }

onLoaded()

mwilcox
  • 4,065
  • 23
  • 20
0

Just to provide an alternative to jQuery, YUI Event provides an onDomReady() function for this purpose as well. Here's the example from their site:

 <script type="text/javascript">

 function init() {
    YAHOO.util.Dom.setStyle("hidden_element", "visibility", "");
 }
 YAHOO.util.Event.onDOMReady(init);

 </script>
Dan Lew
  • 85,990
  • 32
  • 182
  • 176