只要使用过jQuery的,想必对ready都不陌生,$(function(){})和$(document).ready(function(){})的使用更是习以为常。要说到window.onload与document.ready的区别也能谈出个一二,最重要的区别就是:window ...
只要使用过jQuery的,想必对ready都不陌生,$(function(){})和$(document).ready(function(){})的使用更是习以为常。
要说到window.onload与document.ready的区别也能谈出个一二,最重要的区别就是:
window.onload是在dom文档树以及所有文件都加载完成后,才执行;
而document.ready是,只要dom文档树加载完,就执行,且当dom文档树加载完就执行的好处就是,当页面中的图片等外部资源过多时,window.onload迟迟不能触发,这时若还没有绑定事件,用户点击按钮时没有反应,这不影响用户体验么。
咦,Jquery的ready这么牛逼,那Jquery是怎么实现ready这个函数的呢?我们不妨一起来探究探究。
以下Jquery.ready的源码,截自于jQuery 1.12.0。
1 jQuery.ready.promise = function( obj ) { 2 if ( !readyList ) { 3 4 readyList = jQuery.Deferred(); 5 6 // Catch cases where $(document).ready() is called 7 // after the browser event has already occurred. 8 // we once tried to use readyState "interactive" here, 9 // but it caused issues like the one10 // discovered by ChrisS here:11 // http://bugs.jquery.com/ticket/12282#comment:1512 if ( document.readyState === "complete" ) {13 14 // Handle it asynchronously to allow scripts the opportunity to delay ready15 window.setTimeout( jQuery.ready );16 17 // Standards-based browsers support DOMContentLoaded18 } else if ( document.addEventListener ) {19 20 // Use the handy event callback21 document.addEventListener( "DOMContentLoaded", completed );22 23 // A fallback to window.onload, that will always work24 window.addEventListener( "load", completed );25 26 // If IE event model is used27 } else {28 29 // Ensure firing before onload, maybe late but safe also for iframes30 document.attachEvent( "onreadystatechange", completed );31 32 // A fallback to window.onload, that will always work33 window.attachEvent( "onload", completed );34 35 // If IE and not a frame36 // continually check to see if the document is ready37 var top = false;38 39 try {40 top = window.frameElement == null && document.documentElement;41 } catch ( e ) {}42 43 if ( top && top.doScroll ) {44 ( function doScrollCheck() {45 if ( !jQuery.isReady ) {46 47 try {48 49 // Use the trick by Diego Perini50 // http://javascript.nwbox.com/IEContentLoaded/51 top.doScroll( "left" );52 } catch ( e ) {53 return window.setTimeout( doScrollCheck, 50 );54 }55 56 // detach all dom ready events57 detach();58 59 // and execute any waiting functions60 jQuery.ready();61 }62 } )();63 }64 }65 }66 return readyList.promise( obj );67 };
海外公司注册、海外银行开户、跨境平台代入驻、VAT、EPR等知识和在线办理:https://www.xlkjsw.com
原标题:jQuery之ready源码分析
关键词:jquery
*特别声明:以上内容来自于网络收集,著作权属原作者所有,如有侵权,请联系我们:
admin#shaoqun.com
(#换成@)。