How to hook the DOM loaded event?

余生长醉 提交于 2019-12-04 03:50:58

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>

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

document.addEventListener('DOMContentLoaded', function() {
  // ...
})

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>

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()

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!