jquery的ready則是指在頁面的dom模型載入完後執行指定的函數
ready肯定在onload之前發生,頁面載入大或者多的圖片而使onload執行延後,使用jquery的ready可緩解此問題
jquery中如何?
1. ready(fn) 提供給外界的綁定事件的借口。
源碼
ready: function( fn ) {
jquery.bindready(); //添加監聽函數
if ( jquery.isready ) { //如果dom載入完成了
fn.call( document, jquery ); //立刻執行函數
} else if ( readylist ) {
readylist.push( fn ); //否則把函數添加進readylist
}
return this;
},
ready: function() {
if ( !jquery.isready ) {
if ( !document.body ) {
return settimeout( jquery.ready, 13 );
}
jquery.isready = true; //設定isready
if ( readylist ) {
var fn, i = 0;
while ( (fn = readylist[ i++ ]) ) {
fn.call( document, jquery );
}
readylist = null;
}
if ( jquery.fn.triggerhandler ) {
jquery( document ).triggerhandler( "ready" );
}
}
}
bindready() 綁定事件監聽器的方法 屏蔽了瀏覽器的差異
看看bindready的實現
bindready: function() {
if ( readybound ) { //預設為false
return;
}
readybound = true;
if ( document.readystate === "complete" ) {
return jquery.ready();
}
if ( document.addeventlistener ) { document.addeventlistener("domcontentloaded",domcontentloaded, false );
window.addeventlistener( "load", jquery.ready, false );
} else if ( document.attachevent ) {
document.attachevent("onreadystatechange", domcontentloaded);
window.attachevent( "onload", jquery.ready );
var toplevel = false;
try {
toplevel = window.frameelement == null;
} catch(e) {}
if ( document.documentelement.doscroll && toplevel ) {
doscrollcheck();
}
}
}
doscrollcheck() 為ie瀏覽器測試的方法
doscrollcheck
function doscrollcheck() {
if ( jquery.isready ) {
return;
}
try {
document.documentelement.doscroll("left");
} catch( error ) {
settimeout( doscrollcheck, 1 );
return;
}
//不停的執行document.documentelement.doscroll("left")
jquery.ready();
}
4. domcontentloaded() 移除了綁定的domcontentloaded監聽器,並且調用jquery.ready()方法
源碼展示:
domcontentloaded = function() {
document.removeeventlistener( "domcontentloaded", domcontentloaded, false );
jquery.ready();
};
之所以用這個來取代window.onload,就是因為它是在dom模型載入完成後就執行,而window.onload是在dom元素載入完全後才執行
<!doctype html public "-//w3c//dtd xhtml 1.0 transitional//en" "http://www.w3.org/tr/xhtml1/dtd/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="content-type" content="text/html; charset=gb2312" />
<title>kimipolo</title>
</head>
<body>
<img id="test" src="/132149/4908a6389d5f1.jpg">
<script type="text/網頁特效">
if (document.addeventlistener) {
document.addeventlistener("domcontentloaded", init, false);
}
// for internet explorer (using conditional comments)
/*@cc_on @*/
/*@if (@_win32)
document.write("<script id=__ie_onload defer src=javascript:void(0)></script>");
var script = document.getelementbyid("__ie_onload");
script.onreadystatechange = function() {
if (this.readystate == "complete") {
init(); // call the onload handler
}
};
/*@end @*/
window.onload=inits;
function inits(){
idtest=document.getelementbyid('test');
alert('window.onload載入^_^n'+idtest.src);
}
function init(){
idtest=document.getelementbyid('test');
alert('立即載入^_^n'+idtest.src)
}
</script>
</body>
</html>