Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript/jQuery and "top-level" functions

When I peruse a jQuery-driven JavaScript source file, I see functions defined like so:

$(document).ready(function() {
    ...
});

$(function {
    ...
});

I think I understand the first one: I assume its a function to fire once the entire page is downloaded, yes? If not please correct me!

What really confuses me is the second one. Is this an anonymous function? How/where does it get called? When does it get called (page load)?

I guess I'm used to seeing JavaScript function written the old way:

function myFunction() {
    ...
}

Then I just call myFunction anytime I need it. How does this "old" way compare to jQuery's constructs? Thanks for helping me understand any of this confusion!

like image 780
IAmYourFaja Avatar asked Dec 19 '25 03:12

IAmYourFaja


1 Answers

The second function is just a short-hand method for the first method. Both register a callback for the document's "ready" event.

http://api.jquery.com/ready/

All three of the following syntaxes are equivalent:

$(document).ready(handler)
$().ready(handler) (this is not recommended)
$(handler)

EDIT:
The ready event actually fires when the DOM can be safely updated. The event will be raised before external resources like images are fully loaded, but most browsers appear to wait for extenal CSS to finish loading before calling it since scripts often depend on the layout calculations to be complete. The shorthand method jQuery method is very common since it provides an easy to remember and direct method for scripts to change the DOM when it's, well, "ready" for the script.

like image 86
jimp Avatar answered Dec 20 '25 18:12

jimp