What is the advantage of jQuery initialization?

I am currently reading an article on Greg Franco's blog, jQuery Best Practices.

Among his early slides, he explains typical / best / best ways to do things.

Typical ( link )

$("document").ready(function() { console.log('hello world'); }); 

OR

 $(function() { console.log('hello world'); }); 

Better ( link )

 (function($, window, document) { $(function() { console.log('hello world'); }); }(window.jQuery, window, document)); 

The best ( link )

 (function(yourcode) { yourcode(window.jQuery, window, document); }(function($, window, document) { $(function() { console.log('hello world'); }); })); 

So, I think, my question is: what makes the third example better than the second example? Both are IIFE. The only difference I see is that # 2 passes the jQuery object (+ window + document) to IIFE and runs the code, while # 3 passes the jQuery object (+ window + document) and JavaScript code to IIFE. What is the use of this?

+7
javascript jquery iife
source share
1 answer

@Minja,

I believe that a self-generating wrapper function (function () {...} ()) is what the performance trick does.

See the tests below.

I tried to reduce the best code below, which reduced the execution time.

 (function($, window, document) { $(function() { console.log('hello world'); }); }(window.jQuery, window, document)); 

But the lower one reduced him further. Now it is getting better. :)

 (function(){ (function($, window, document) { $(function() { console.log('hello world'); }); }(window.jQuery, window, document)); }()) 

See the screenshot below for proof: enter image description here

0
source share

All Articles