How does:
(function($) {
/// code
})(jQuery)
differ from $(document).ready(function() in jquery?
I know what the ready function does. It awaits until the HTML is loaded before it starts. However, does (function($) do the same?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
the “shorthand” for
$(document).ready()is simply$():However, your first code is NOT the same as
.ready(). What you have there is an immediately-invoked function expression (IIFE), or in layman’s terms, “run this function immediately”This is just equal to something like this “function-and-call” but without the function name (an anonymous function) and the call:
this method is often used to protect code that uses
$for jQuery while other libraries are using the same$function name, thus prevent conflicts. jQuery just uses$for a shorthand alias tojQuery(you would not want to typejQuery('selector')all the time,$('selector')is shorter)