Firefox、Opera、およびWebkitベースのブラウザには、でDOMContentLoaded
リッスンできるドキュメントレベルのイベントがありますdocument.addEventListener("DOMContentLoaded", fn, false)
。
IEではもっと複雑です。IEでjQueryが行うことonreadystatechange
は、document.onloadイベントのバックアップを使用して特定のreadystateをドキュメントオブジェクトで監視することです。document.onloadは、DOMの準備が整うよりも遅く起動するため(すべてのイメージの読み込みが完了した場合のみ)、以前のイベントが何らかの理由で機能しない場合のバックストップとしてのみ使用されます。
グーグルに時間を費やすと、これを行うためのコードが見つかります。これを行うための最も精査されたコードはjQueryやYUIのような大きなフレームワークにあると思うので、そのフレームワークを使用していなくても、それらのソースコードでテクニックを調べます。
jQuery1.6.2のソースの主要部分は次のdocument.ready()
とおりです。
bindReady: function() {
if ( readyList ) {
return;
}
readyList = jQuery._Deferred();
// Catch cases where $(document).ready() is called after the
// browser event has already occurred.
if ( document.readyState === "complete" ) {
// Handle it asynchronously to allow scripts the opportunity to delay ready
return setTimeout( jQuery.ready, 1 );
}
// Mozilla, Opera and webkit nightlies currently support this event
if ( document.addEventListener ) {
// Use the handy event callback
document.addEventListener( "DOMContentLoaded", DOMContentLoaded, false );
// A fallback to window.onload, that will always work
window.addEventListener( "load", 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", DOMContentLoaded );
// A fallback to window.onload, that will always work
window.attachEvent( "onload", jQuery.ready );
// If IE and not a frame
// continually check to see if the document is ready
var toplevel = false;
try {
toplevel = window.frameElement == null;
} catch(e) {}
if ( document.documentElement.doScroll && toplevel ) {
doScrollCheck();
}
}
},