Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

failsafe jQuery code

Tags:

jquery

Can anyone explain what the jquery documentation is exactly referring to with this statement: "the argument to write failsafe jQuery code using the $ alias, without relying on the global alias" when referring to using the following:

    jQuery(function($) {
});

I have been using jquery for a while now so understand what this code is doing to a certain extent but the phrase used in the documentation about writing failsafe jquery code puzzles me and i am unsure whether it is important or not.

like image 911
David Avatar asked Jun 05 '10 23:06

David


1 Answers

The $ variable name is not unique to jQuery - other javascript libraries also make use of it. If you are using both on the same page (perhaps not intentionally - another library could be pulled in by a third party script) then there is a risk that the variable you think points to a jQuery object actually points to something else meaning your code will break as the API you are working to won't exist.

What this code does is use the global jQuery function (which doesn't clash with any other library) to which is passed an anonymous function receiving the main jQuery object as a parameter. Because this parameter is scoped to the function and not globally, nothing outside the function can interfere with it, and you can code with it safe in the knowledge that it will only ever be a jQuery object unless you override it yourself.

like image 87
Luke Bennett Avatar answered Nov 05 '22 04:11

Luke Bennett