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 };
  • 相关阅读:
    项目启动报错:No suitable driver found for jdbc:oracle:thin:@192.168.7.146:1521:oracle
    (八)Oracle学习笔记—— 触发器
    (七)Oracle学习笔记—— 游标
    spring自动装配(No qualifying bean )
    Intellij output 中文乱码
    使用Spring开发和监控线程池服务
    IDEA在编辑时提示could not autowire
    java 过滤器(Filter)与springMVC 拦截器(interceptor)的实现案例
    Java过滤器(Filter)与SpringMVC拦截器(Interceptor)之间的关系与区别
    idea 添加多模块项目
  • 原文地址:https://www.cnblogs.com/zccst/p/3749617.html
Copyright © 2011-2022 走看看