document.ready like functionality in javascript?

最后都变了- 提交于 2019-12-12 02:18:49

问题


I have a requirement that states to use only plain JavaScript and not jQuery. I need to initialize some variables(using some function) as soon as the DOM is loaded and not when the page has fully loaded. In short it should not wait for the whole page to load. In jQuery it can be very easily done using document.ready() function.

Is it possible to implement it in JavaScript using any function?


回答1:


a "practical" way is just placing a script block before the end of the document (even is not really equivalent to domready)

  ...
  <script>...</script>
  </body>
</html>

or use one of various pure-js implementation of DomReady event, like http://snipplr.com/view/6029/domreadyjs/




回答2:


It's sometimes achieved like this

<body>
<!--
All your html tags here
....
....
-->



    <script type="text/javascript">
      //this should execute after the above tags and elements have rendered
    </script>
</body>



回答3:


You can use DOMContentLoaded event if supported:

MSDN: http://msdn.microsoft.com/en-us/library/windows/apps/hh868490.aspx

MDN: https://developer.mozilla.org/en/DOM/DOM_event_reference/DOMContentLoaded




回答4:


if you realy want to wait for "ready event" you can for example use that kind of thing :

    (function(w,evt,fn){
        if (w.addEventListener){// W3C DOM
            w.addEventListener(evt,fn,false);
        }
        else if (w.attachEvent) { // IE DOM
            w.attachEvent("on"+evt, fn);
        }

    })(window,'load',function(){
       // your code here
    });

but it's indeed better to simply use a well placed 'script' tag as your code will probably work and start sooner



来源:https://stackoverflow.com/questions/11739128/document-ready-like-functionality-in-javascript

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