jQueryを使わずに$(document).readyと同等のもの 質問する

jQueryを使わずに$(document).readyと同等のもの 質問する

を使用するスクリプトがあります$(document).readyが、jQuery の他の部分は使用していません。jQuery の依存関係を削除して軽量化したいと思います。

$(document).readyjQuery を使用せずに独自の機能を実装するにはどうすればよいですか?すべての画像、フレームなどが読み込まれた後に実行されるwindow.onloadため、使用した場合と同じではないことはわかっています。window.onload

ベストアンサー1

標準ベースの代替品があり、DOMContentLoadedそれはブラウザの99%ただし、IE8 ではありません:

document.addEventListener("DOMContentLoaded", function(event) { 
  //do work
});

以下に示すように、jQuery のネイティブ関数は単なる window.onload よりもはるかに複雑です。

function bindReady(){
    if ( readyBound ) return;
    readyBound = true;

    // Mozilla, Opera and webkit nightlies currently support this event
    if ( document.addEventListener ) {
        // Use the handy event callback
        document.addEventListener( "DOMContentLoaded", function(){
            document.removeEventListener( "DOMContentLoaded", arguments.callee, false );
            jQuery.ready();
        }, false );

    // If IE event model is used
    } else if ( document.attachEvent ) {
        // ensure firing before onload,
        // maybe late but safe also for iframes
        document.attachEvent("onreadystatechange", function(){
            if ( document.readyState === "complete" ) {
                document.detachEvent( "onreadystatechange", arguments.callee );
                jQuery.ready();
            }
        });

        // If IE and not an iframe
        // continually check to see if the document is ready
        if ( document.documentElement.doScroll && window == window.top ) (function(){
            if ( jQuery.isReady ) return;

            try {
                // If IE is used, use the trick by Diego Perini
                // http://javascript.nwbox.com/IEContentLoaded/
                document.documentElement.doScroll("left");
            } catch( error ) {
                setTimeout( arguments.callee, 0 );
                return;
            }

            // and execute any waiting functions
            jQuery.ready();
        })();
    }

    // A fallback to window.onload, that will always work
    jQuery.event.add( window, "load", jQuery.ready );
}

おすすめ記事