Getting notified when the page DOM has loaded (but before [removed])

前端 未结 9 901
北恋
北恋 2020-12-09 06:37

I know there are some ways to get notified when the page body has loaded (before all the images and 3rd party resources load which fires the window.onload e

9条回答
  •  情书的邮戳
    2020-12-09 07:16

    The fancy crossbrowser solution you are looking for....doesn't exist... (imagine the sound of a big crowd saying 'aahhhh....').

    DomContentLoaded is simply your best shot. You still need the polling technique for IE-oldies.

    1. Try to use addEventListener;
    2. If not available (IE obviously), check for frames;
    3. If not a frame, scroll until no error get's thrown (polling);
    4. If a frame, use IE event document.onreadystatechange;
    5. For other non-supportive browsers, use old document.onload event.

    I've found the following code sample on javascript.info which you can use to cover all browsers:

    function bindReady(handler){
    
        var called = false
    
        function ready() { 
            if (called) return
            called = true
            handler()
        }
    
        if ( document.addEventListener ) { // native event
            document.addEventListener( "DOMContentLoaded", ready, false )
        } else if ( document.attachEvent ) {  // IE
    
            try {
                var isFrame = window.frameElement != null
            } catch(e) {}
    
            // IE, the document is not inside a frame
            if ( document.documentElement.doScroll && !isFrame ) {
                function tryScroll(){
                    if (called) return
                    try {
                        document.documentElement.doScroll("left")
                        ready()
                    } catch(e) {
                        setTimeout(tryScroll, 10)
                    }
                }
                tryScroll()
            }
    
            // IE, the document is inside a frame
            document.attachEvent("onreadystatechange", function(){
                if ( document.readyState === "complete" ) {
                    ready()
                }
            })
        }
    
        // Old browsers
        if (window.addEventListener)
            window.addEventListener('load', ready, false)
        else if (window.attachEvent)
            window.attachEvent('onload', ready)
        else {
            var fn = window.onload // very old browser, copy old onload
            window.onload = function() { // replace by new onload and call the old one
                fn && fn()
                ready()
            }
        }
    }
    

提交回复
热议问题