jquery源码解析之ready与load事件

xiaoxiao2021-02-27  271

1.DOM加载的步骤

    网页渲染的过程主要分为以下几步:1.解析HTML结构;2.加载外部脚本和样式表文件3.解析并执行脚本代码;4.构造HTML DOM模型;5加载图片等外部文件;6.页面加载完毕。ready主要是在第4步完成之后执行的,load要在第6步完成之后执行。所以是ready先执行load后执行。

2.jQuery中ready事件

ready: function( fn ) { // 添加回调函数 jQuery.ready.promise().done( fn ); return this; } jQuery.ready.promise = function( obj ) { if ( !readyList ) { readyList = jQuery.Deferred(); //判断页面是否已经全部加载完成,直接调用ready方法 if ( document.readyState === "complete" ) { // Handle it asynchronously to allow scripts the opportunity to delay ready setTimeout( jQuery.ready, 1 ); // 标准浏览器支持DOMContentLoaded } else if ( document.addEventListener ) { // 监听DOM是否已经加载完成 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 { // 针对于低版本的IE浏览器 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 top = false; try { top = window.frameElement == null && document.documentElement; } catch(e) {} if ( top && top.doScroll ) { (function doScrollCheck() { if ( !jQuery.isReady ) { try { top.doScroll("left"); } catch(e) { return setTimeout( doScrollCheck, 50 ); } // and execute any waiting functions jQuery.ready(); } })(); } } } return readyList.promise( obj ); };

             

转载请注明原文地址: https://www.6miu.com/read-4002.html

最新回复(0)