Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery scripts: function(window, document, undefined) vs ;(function($, window, document, undefined) [duplicate]

I have seen some jQuery scripts embedded in webpages that open with

(function(window, document, undefined){...

or

;(function ( $, window, document, undefined ) {...

I believe the ; could be there if the script is concatenated with other files and there is a missing closing bracket, the ; stops the minifier from removing the first lines of the code, but I am not sure.

Whats up with the two variants I posted? Why do people open their code like this, why is the first example missing the dollar sign?

like image 480
Sven Avatar asked Feb 22 '13 17:02

Sven


1 Answers

Those are wrappers to create an environment for a script that is as predictable as possible.

At the end of the script you will see the closing bracket for the function expression, and the immediate call to the function that sends in values for the parameters defined in the function signature:

(function($, window, document, undefined){
 ...
})(jQuery, window, document);

If you use jQuery you would include the $ parameter for it, otherwise not. (Or if you didn't think of including it.)

As you see, there isn't any value for the parameter named undefined. When you don't pass a value for a parameter, it will be set to the value undefined, so inside the function block the parameter named undefined will have the value undefined. The purpose of this is because the global identifier undefined wasn't a constant until recent versions of Javascript, so in older browsers you can give the property undefined a value so that it doesn't represent undefined any more. (Note that the parameter without a value defined will get the actual value undefined, not the current value of the global property undefined.)

As you suspected, the extra semicolon at the beginning is to protect the script from other scripts that it might be merged with.

like image 141
Guffa Avatar answered Sep 23 '22 21:09

Guffa