3

The application I am looking at loads an external javascript file which looks like this:

$(function () {

    // Don't allow browser caching of forms
    $.ajaxSetup({ cache: false });

    var dialogs = {};

    var getValidationSummaryErrors = function ($form) {
        // We verify if we created it beforehand
        ...
        ...
        }
        return errorSummary;
    };

I understand that the file setups up some variables and also declares a function called getValidationSummaryErrors.

What I don't understand is why is this all within

$(function () {  ... }

What's the purpose of this? Can I not just declare the variable and things inside the flat file without the "$(function () { }" ?

dtbarne
  • 8,110
  • 5
  • 43
  • 49

4 Answers4

7

$(function() { ... }); is just short for $(document).ready(function() { ... });, which ensures that the code is not executed until the DOM is ready, otherwise some code that affects the DOM may not work properly.

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

dtbarne
  • 8,110
  • 5
  • 43
  • 49
  • 1
    It also avoids polluting the global namespace. – Matt Ball Apr 22 '12 at 05:47
  • True, but you don't need jQuery for that. A `(function() { ... })()` used properly would do. – dtbarne Apr 22 '12 at 05:50
  • 2
    This is precisely why I'd rather see people use `$(document).ready(function() {...})` instead of `$(function() { ... });` because the former is so much more obvious what it does. – jfriend00 Apr 22 '12 at 06:04
  • I suggest to use something like `jQuery(function($) { ... });` because you build a automatic noConflict system and you always can use the normal `$` in the code inside this function. – Wouter J Apr 22 '12 at 06:51
3
$(function () {  ... });

Means that the function will run after the page (DOM part) is loaded, not when the code gets parsed. This you can make sure that the page is loaded faster, and also everything necessary is available for the javascript to run.

ther
  • 848
  • 8
  • 16
3

$() is shortcut for jQuery.ready(), which executes code after page DOM is fully loaded. Sometimes you want to make sure that document is ready before you do certain things.

valentinas
  • 4,277
  • 1
  • 20
  • 27
2

This is a concise notation for $(document).ready(function() {...}) ". NOTE : the jQuery document ready fires when the DOM has been loaded. It doesn't wait for entire page (included images and the like) to load.

Practically, any script that you put into the <head> executes immediately i.e. if the Script interacts with the DOM it needs to be ready.

Thirdly it is needed for separations of concerns. Ideally your javaScript and HTML are in separate files. If you follow this you will not have any in-line script tags in your HTML at all.

Ananda Sudarshan
  • 485
  • 5
  • 10