Reputation: 255
I came across a public JavaScript fragment that has the following lines of code:
$(function() {
var v1, v2;
v1 = new V1;
return v2 = new V2(v1);
});
The guts of the function are perfectly grokkable. But what is the significance of wrapping this in a $()
?
Upvotes: 1
Views: 109
Reputation: 100321
$( fn )
is a shortcut for $(document).ready( fn )
, which executes fn
when the DOMContent is loaded.
In .ready
docs you can see that these 3 are equivalent
$(document).ready(handler)
$().ready(handler) // this one is not recommended
$(handler)
With pure Javascript you could achieve the same behavior using
document.addEventListener("DOMContentLoaded", fn, false);
jQuery docs:
Upvotes: 1
Reputation: 74420
$(function() {...});
is a shorthand for $(document).ready(function(){...});
This means code inside will be executed as soon as DOM is ready. BTW its jquery syntax, there is no really pure javascript equivalent. It is not equivalent to window.onload = function(){...}
which in jquery would be wrote: $(window).load(function(){...});
.
Don't be fooled by auto called anonymous function used in javascript:
(function(){...})()
or
(function(){...}())
Upvotes: 4
Reputation: 2823
That notation is alias for $(document).ready(function() { ... });
Upvotes: 0