Dom loaded event cross borwser native javascript code

雨燕双飞 提交于 2019-12-28 06:53:34

问题


I'm working without the javascript framework, but I want to call a function just when the DOM is loaded.

I can't/don't want to use the attribute 'onload' on the < body > tag.


回答1:


Here is the code:

  • in non-IE browsers, use DOMContentLoaded event
  • in IE top frame use scroll hack (see _readyIEtop)
  • in IE frame, simply use onload

    var onready = function(handler) {
        // window is loaded already - just run the handler
        if(document && document.readyState==="complete") return handler();
    
        // non-IE: DOMContentLoaded event
        if(window.addEventListener) window.addEventListener("DOMContentLoaded",handler,false);
    
        // IE top frame: use scroll hack
        else if(window.attachEvent && window==window.top) { if(_readyQueue.push(handler)==1) _readyIEtop(); }
    
        // IE frame: use onload
        else if(window.attachEvent) window.attachEvent("onload",handler);
    };
    
    // IE stuff
    var _readyQueue = [];
    var _readyIEtop = function() {
        try {
          document.documentElement.doScroll("left");
          var fn; while((fn=_readyQueue.shift())!=undefined) fn();
        }
        catch(err) { setTimeout(_readyIEtop,50); }
    };
    

jQuery tunes the IE a little more (lots of code), but in my tests it runs just before onload event anyway.

var test = function() { alert("ok"); }
onready(test);



回答2:


I think http://code.google.com/p/domready/ is exactly what you're looking for.

If you are ever writing your own JavaScript file that cannot depend on the existing libraries out there and would like to execute only after the page is loaded, this library is for you.

Simply do this:

<html lang="en">
<head>
        <script src="domready.js" type="application/javascript"></script>
        <script type="application/javascript">
                DomReady.ready(function() {
                    alert('dom is ready');
                });
        </script>
</head>
<body>

</body>
</html>



回答3:


Well, I'm afraid cross-browser and DOM loaded don't go together easily. By recommendation is Ryan Morr's ondomready (https://github.com/ryanmorr/ondomready) but there are a ton of alterntives.



来源:https://stackoverflow.com/questions/8181061/dom-loaded-event-cross-borwser-native-javascript-code

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