domReady方法(dom加载完成执行回调)

Posted codeing or artist ?

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了domReady方法(dom加载完成执行回调)相关的知识,希望对你有一定的参考价值。

var domReady = function( fn ) {

    var isReady = false,

        ready = function(){
            if(!isReady){
                typeof fn === ‘function‘ && fn.call(document);
                isReady = true;
            }
        },

        DOMContentLoaded = function() {
            if ( document.addEventListener ) {
                document.removeEventListener( "DOMContentLoaded", DOMContentLoaded, false );
                ready();
            } else if ( document.readyState === "complete" ) {
                document.detachEvent( "onreadystatechange", DOMContentLoaded );
                ready();
            }
        };
    
    if ( document.readyState === "complete" ) {
        setTimeout( ready, 1 );
    } else if ( document.addEventListener ) {
        document.addEventListener( "DOMContentLoaded", DOMContentLoaded, false );
        window.addEventListener( "load", ready, false );
    } else {
        document.attachEvent( "onreadystatechange", DOMContentLoaded );
        window.attachEvent( "onload", ready );


        var top = false;

        try {
            top = window.frameElement == null && document.documentElement;
        } catch(e) {}

        if ( top && top.doScroll ) {
            (function doScrollCheck() {
                if ( !isReady ) {
                    try {
                        top.doScroll("left");
                    } catch(e) {
                        return setTimeout( doScrollCheck, 50 );
                    }

                    ready();
                }
            })();
        }
    }
};


//调用
domReady(function(){
    alert(this.getElementById(‘div1‘).innerhtml);
});

 

以上是关于domReady方法(dom加载完成执行回调)的主要内容,如果未能解决你的问题,请参考以下文章

js dom元素加载完成执行

Dojo 1.10笔记3 等待DOM加载完成

onload与ready差异

回调函数的使用场合

DOM Ready 详解

解决vue解析出现闪烁