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 };
  • 相关阅读:
    windows系统调用 互斥体mutex
    windows系统调用 利用事件对象实现进程通信
    windows系统调用 调度优先级
    <十四>JDBC_c3p0数据库连接池
    <十三>JDBC_dbcp数据库连接池
    <十二>JDBC_批量处理
    <十一>JDBC_事务的处理+隔离
    <十>JDBC_处理Blob类型数据
    <八>JDBC_重构DAO查询方法
    <七>JDBC_使用beanutils工具类操作javaBean
  • 原文地址:https://www.cnblogs.com/zccst/p/3749617.html
Copyright © 2011-2022 走看看