立即调用函数表达式和文档就绪函数

时间:2017-12-18 22:33:22

标签: javascript jquery

在使用jQuery的Javascript中,我可以使用Immediately Invoked Function Expression向函数添加范围并传递函数jQuery,并将参数命名为$

(function ( $ ) { 

    $.fn.greenify = function() {
        this.css( "color", "green" );
        return this;
    }; 

}( jQuery ));

同样,我们编写文档就绪函数,如下所示

$(function() {
    console.log( "ready!" );
    // use $ variable here
});

这是否意味着文档就绪功能已经作用域? 我是否还需要传递函数jQuery,并在文件就绪函数中命名参数$?类似下面的内容

$(function ( $ ) {
    console.log( "ready!" ); 
    // use $ variable here   
 }( jQuery ));

1 个答案:

答案 0 :(得分:0)

立即调用IIFE,它不会等待document做好准备。所以:

(function($) {

    // here document is not necessarly ready

})(jQuery);

执行$(function() { ... });时,您没有创建IIFE,只需传递一个函数(回调),以便在document准备就绪时执行。

如果您想同时执行这两项操作,请使用:

(function($) {

    $(function() {

        // here, document is really ready
        // $ available here too

    });

})(jQuery);

或者这样做(使用jQuery passes itself as parameter to its ready callback):

jQuery(function($) {

    // here, document is really ready
    // and $ is obviously available (only here)

});
相关问题