Why declare inside $ (function () {...})?

In the application I'm viewing, an external javascript file is loaded, 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 configures some variables, and also declares a function called getValidationSummaryErrors.

I do not understand why this is all inside

$(function () {  ... }

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

+3
source share
4 answers

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

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

+8
source
$(function () {  ... });

, ( DOM), . , , javascript.

+4

$() jQuery.ready(), DOM. , , .

+4

$(document).ready(function() {...}) ". . jQuery , DOM . 't ( ..) .

Almost any script that you embed in <head>is executed immediately, i.e. if the script interacts with the DOM, it should be ready.

Thirdly, it is necessary to separate the problems. Ideally, your javaScript and HTML are in separate files. If you follow this, you will not have any inline script tags in your HTML.

+2
source

All Articles