你的位置:首页 > 软件开发 > Java > jquery的ready事件的实现机制浅析

jquery的ready事件的实现机制浅析

发布时间:2015-11-10 15:01:13
页面初始化中,用的较多的就是$(document).ready(function(){//代码}); 或 $(window).load(function(){//代码});他们的区别就是,ready是在DOM的结构加载完后就触发,load是在页面内包括DOM结构,css,js,图 ...

页面初始化中,用的较多的就是$(document).ready(function(){//代码}); 或 $(window).load(function(){//代码});

他们的区别就是,ready是在DOM的结构加载完后就触发,load是在页面内包括DOM结构,css,js,图片等都加载完成后再触发,显然ready更适合作为页面初始化使用。但有时候也不尽然。需要进一步查看其内部机制。

那么ready的内部是如何判断DOM的结构加载完的?并且不同的浏览器的判断是如何的?

 

答案就在jquery代码内,假设jquery的版本是jquery-1.11.3.js。

ready的关键代码(3507~3566行),关键代码用红色标出:

jQuery.ready.promise = function( obj ) {  if ( !readyList ) {    readyList = jQuery.Deferred();    // Catch cases where $(document).ready() is called after the browser event has already occurred.    // we once tried to use readyState "interactive" here, but it caused issues like the one    // discovered by ChrisS here: http://bugs.jquery.com/ticket/12282#comment:15    if ( document.readyState === "complete" ) {      // Handle it asynchronously to allow scripts the opportunity to delay ready      setTimeout( jQuery.ready );    // Standards-based browsers support DOMContentLoaded    } else if ( document.addEventListener ) {      // Use the handy event callback      document.addEventListener( "DOMContentLoaded", completed, false );      // A fallback to window.onload, that will always work      window.addEventListener( "load", completed, false );    // If IE event model is used    } else {      // Ensure firing before onload, maybe late but safe also for iframes      document.attachEvent( "onreadystatechange", completed );      // A fallback to window.onload, that will always work      window.attachEvent( "onload", completed );      // If IE and not a frame      // continually check to see if the document is ready      var top = false;      try {        top = window.frameElement == null && document.documentElement;      } catch(e) {}      if ( top && top.doScroll ) {        (function doScrollCheck() {          if ( !jQuery.isReady ) {            try {              // Use the trick by Diego Perini              // http://javascript.nwbox.com/IEContentLoaded/              top.doScroll("left");            } catch(e) {              return setTimeout( doScrollCheck, 50 );            }            // detach all dom ready events            detach();            // and execute any waiting functions            jQuery.ready();          }        })();      }    }  }  return readyList.promise( obj );};

 

海外公司注册、海外银行开户、跨境平台代入驻、VAT、EPR等知识和在线办理:https://www.xlkjsw.com

原标题:jquery的ready事件的实现机制浅析

关键词:jquery

*特别声明:以上内容来自于网络收集,著作权属原作者所有,如有侵权,请联系我们: admin#shaoqun.com (#换成@)。

可能感兴趣文章

我的浏览记录