Yan Yi
Yan Yi

Reputation: 773

Purpose of wrapping with anonymous function

I'm building a chrome extension and included the following code in my content script. pep is a library for making things draggable. Interestingly, my code worked for case #2 but not #1. Why is that so?

It seems like the second case is wrapping the function call with an anonymous function (although I'm not sure why the jquery is needed before that)

//1
$('#square').pep();

//2
$(function($) {
    $('#square').pep();
});

Upvotes: 0

Views: 123

Answers (3)

marekful
marekful

Reputation: 15361

A function passed to jQuery constructor, $(function() {}), is a shorthand for $(document).ready(function() {});

The function argument doesn't have to be anonymous, in fact, it's a good practice to always name such functions like so $(function myDomReady() {}).

Upvotes: 1

jared_flack
jared_flack

Reputation: 1646

The second case is jQuery's shorthand for "on document ready".

It's the equivalent of:

$(document).ready(function() {
    $('#square').pep();
});

Documentation: https://api.jquery.com/ready/

Upvotes: 7

In the second case you are using a shorthand for $(document).ready(). That way the javascript waits for all the DOM elements to load before executing. The library needs all element to be loaded in order to work.

https://learn.jquery.com/using-jquery-core/document-ready/

Upvotes: 1

Related Questions