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 () { }" ?
-
Maybe also something with closurehackartist– hackartist2012年04月22日 05:46:45 +00:00Commented Apr 22, 2012 at 5:46
-
JavaScript is a dangerously powerful language. I recommend you to view Doug Crockford 's video if you haven't. youtube.com/watch?v=hQVTIJBZookRay Cheng– Ray Cheng2012年04月22日 05:56:45 +00:00Commented Apr 22, 2012 at 5:56
-
Closure explained in non-technical term. stackoverflow.com/a/6472397/310767Ray Cheng– Ray Cheng2012年04月22日 06:02:53 +00:00Commented Apr 22, 2012 at 6:02
4 Answers 4
$(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.
4 Comments
(function() { ... })() used properly would do.$(document).ready(function() {...}) instead of $(function() { ... }); because the former is so much more obvious what it does.jQuery(function($) { ... }); because you build a automatic noConflict system and you always can use the normal $ in the code inside this function.$() 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.
Comments
$(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.
Comments
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.