2

i have read that (function(){})(); is called immediately and doesn't need to be called. and $(function()); is also immediately called.

  • are they both and have same functionality ?
  • does the Immediately-Invoked Function loaded after the document is completely loaded ?
  • what is the actual functionality of $(function()); ?
  • does $(function()); after the document is completely loaded ?
BenMorel
  • 34,448
  • 50
  • 182
  • 322
Iori
  • 660
  • 1
  • 10
  • 19

2 Answers2

9
$(function(){}); 

isn't immediately called : it is called when the DOM is ready. It's a shortcut for

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

See documentation

Denys Séguret
  • 372,613
  • 87
  • 782
  • 758
  • What is it equivalent to in vanilla JavaScript? OnLoad()? – 1252748 Nov 24 '13 at 02:49
  • @thomas The best equivalent of ready would be [onreadystatechange](https://developer.mozilla.org/en-US/docs/Web/API/document.readyState) but most often, if you don't need the resources to be loaded, the simplest solution is to call your code from a script element at the end of the body (when the elements have already been defined). – Denys Séguret Nov 24 '13 at 08:48
1

(function () {})() is an anonymous function that is immediately called.

$(function () {}); is jQuery shorthand for $(document).ready(function () {});

MattDiamant
  • 8,561
  • 4
  • 37
  • 46