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 $()?
4 Answers 4
$(fn) is a shortcut for $(document).ready(fn).
3 Comments
ready event."$(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(){...}())
$( 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:
Comments
That notation is alias for $(document).ready(function() { ... });