zoukankan      html  css  js  c++  java
  • $(function(){})的执行过程分析

    作者:zccst

    首先,$(function(){})是$(document).ready(function(){})的简写形式。

    在日常使用中,我们会把代码写到$(function(){})中,今天看看jQuery是如何做的(过程有点长)。

    1,看jQuery入口,结论是$(function(){})是$(document).ready(function(){})的简写形式

    $(function(){})相对于$()中传入了一个function类型的数据。根据源码:

    jQuery.fn = jQuery.prototype = {

        init:function( selector, context, rootjQuery ) {

            if ( jQuery.isFunction( selector ) ) {
                return rootjQuery.ready( selector );
            }

        }

    }

    而rootjQuery就是$(document),见866行源码

    // All jQuery objects should point back to these
    rootjQuery = jQuery(document);

    2,$(document).ready(function(){})是如何实现的呢?

    从$().ready()的调用方式可以看出,ready是对象方法,见240行源码

    ready: function( fn ) {
        // Add the callback
        jQuery.ready.promise().done( fn );

        return this;
    },

    可以看出,jQuery.ready.promise()是一个对象,调用了done(fn)方法,表明调用了一个延迟对象,再看一下jQuery.ready.promise()

     1 jQuery.ready.promise = function( obj ) {
     2     if ( !readyList ) {
     3 
     4         readyList = jQuery.Deferred();
     5 
     6         // Catch cases where $(document).ready() is called after the browser event has already occurred.
     7         // we once tried to use readyState "interactive" here, but it caused issues like the one
     8         // discovered by ChrisS here: http://bugs.jquery.com/ticket/12282#comment:15
     9         if ( document.readyState === "complete" ) {
    10             // Handle it asynchronously to allow scripts the opportunity to delay ready
    11             setTimeout( jQuery.ready );//调用工具方法jQuery.ready
    12 
    13         } else {
    14 
    15             // Use the handy event callback
    16             document.addEventListener( "DOMContentLoaded", completed, false );
    17 
    18             // A fallback to window.onload, that will always work
    19             window.addEventListener( "load", completed, false );//回调函数在90行,也调用工具方法jQuery.ready
    20         }
    21     }
    22     return readyList.promise( obj );
    23 };
  • 相关阅读:
    toj 2819 Travel
    toj 2807 Number Sort
    zoj 2818 Prairie dogs IV
    zoj 1276 Optimal Array Multiplication Sequence
    toj 2802 Tom's Game
    toj 2798 Farey Sequence
    toj 2815 Searching Problem
    toj 2806 Replace Words
    toj 2794 Bus
    css截取字符
  • 原文地址:https://www.cnblogs.com/zccst/p/3749617.html
Copyright © 2011-2022 走看看