$(document).ready() と 書いても $(window).ready() と書いても同じ事になります。
内部では、IE と Gecko で実装は違いますが、いずれも document のイベントです。
Gecko-Specific DOM Events - MDC Doc Center でそのイベントについて書かれていて、
「"load" とは異なり画像が読み込まれるのを待ちません」とあります。で、何故か日本
語ページの訳が間違っていて、window のイベントと書かれていますが、英文ページでは
document オブジェクトのイベントと書かれており、jQuery でもそう扱われています。
IE のほうは、onreadystatechange Event とあって、これも document オブジェクト
のイベントでかなり前から実装されていたようです。
いずれも、それらのイベントで仮に失敗しても確実な window の load イベントでフォ
ローするという念の入った実装となっています。
$(window).load は、そのままで window の onload イベントの実装に使われています。
$(document).ready() は、通常の onload イベントの実装と比較しましたがとてもうまく
動作しており、$(window).load も正しく動作する事を確認しています
( 通常の登録より後に実行される事を確認済です )
bindReady: function() {
if ( readyBound ) {
return;
}
readyBound = true;
// 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();
}
}
},
以下は、prototype.js における window の onload イベントの実装用の記述ですが、
prototype.js と jQuery を混在させる為に jQuery の $ メソッドを $j にリネーム
してテストしています。
Event.observe(window, 'load', function(){ alert("prototype") });
jquery-1.4.4.min.js の場合、3箇所の変更で、E.$ を E.$j に変更します。
$j(document).ready(function() {
try {
console.log("ready");
}
catch(e){}
$j("#box1").html("<div style='padding: 3px 0 0 6px;'><a href='../'>ホーム</a></div>");
$j("#footer").html("<address>Copyright (c) 2010 xxx All Rights Reserved.</address>");
});
以下は、混在コード内で通常のオブジェクト参照の使用です
Event.observe(window, 'load', function(){
alert( $j("#box1").html() );
alert( $j("#box1")[0].innerHTML );
$j("#box1").each( function(index) {
alert(index + ': ' + this.innerHTML );
alert(index + ': ' + $j(this).html());
});
});
$j(document).ready(function(){
// prototype 参照
alert( $("box1").innerHTML );
})
posted by
at 2010-11-19 22:28
|
JavaScript
|

|