Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What exactly does !function ($){...}(window.jQuery) do?

I'd like to know exactly what's going on here. I know what $(document).ready(function() {...}); does and when it comes into effect. Same goes for jQuery(function($) {...}.

But what does this do?

!function ($) {
  $(function(){
    var $window = $(window)
    //normal jquery stuff
  })
}(window.jQuery)

Is it loaded when jQuery is loaded instead of when the document is 'ready'?

like image 793
Archonic Avatar asked Apr 23 '26 05:04

Archonic


2 Answers

It creates a closure in which the variable $ is assigned the value of window.jQuery.

The intention is to allow the uninformatively named variable $ to be used as a shortcut for jQuery without conflicting with the large number of other libraries and custom functions that also use $ as a variable name.

like image 134
Quentin Avatar answered Apr 24 '26 18:04

Quentin


Using the ! operator before the function causes it to be treated as an expression

!function () {}()
like image 44
Gurpreet Singh Avatar answered Apr 24 '26 18:04

Gurpreet Singh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!