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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With