This code:
<script type="text/javascript">
someMethod1();
$(function () {
someMethod2();
});
</script>
What is the difference between these two callings? When do we do the first call, and when do we do the second call? What is the order of the method execution?
someMethod1();
This might be called before or after document is ready and it does not require jQuery. If this is at the end of your page it will be called when all control are ready but if it is in middle then it will know only controls that got rendered.
$(function () {
someMethod2();
});
This is call always after the document gets ready and all the controls are ready/rendered. This requires jQuery. You can read more about ready here. This will also help you understand the other function call.
someMethod1 is executed immediately
someMethod2 waits for the whole page to load,
including external javascript files (other scripts, or from other sites), CSS
and other resources before executing the code.
$(function () {
//run after page loads
});
Method2 sometimes comes in the form of
$(document).ready(function() {
// Handler for .ready() called.
});
For more info: http://api.jquery.com/ready/
The statements in the script block are executed in the order in which they occur. If we number the lines and insert an extra line break or two to make it easier to talk about:
1 someMethod1();
2
3 $(
4 function () {
5 someMethod2();
6 }
7 );
Line 1, someMethod1() is executed first.
Then line 3, $() is executed, where the parameter to $() is an anonymous function defined on lines 4 to 6. The $() function schedules that anonymous function to be executed later in response to the document ready event. That is, the anonymous function is not executed at that time.
Finally, when the document is ready, the anonymous function from lines 4 to 6 is executed which means line 5 someMethod2() occurs.
Related
Sometimes I make a function and call the function later.
Example:
function example { alert('example'); }
example(); // <-- Then call it later
Somehow, some functions cannot be called. I have to call those functions inside:
$(function() { });
What do $(function() {}); and (function() { }); mean, and what's the difference/purpose of these?
$(function() { ... });
is just jQuery short-hand for
$(document).ready(function() { ... });
What it's designed to do (amongst other things) is ensure that your function is called once all the DOM elements of the page are ready to be used.
However, I don't think that's the problem you're having - can you clarify what you mean by 'Somehow, some functions are cannot be called and I have to call those function inside' ?
Maybe post some code to show what's not working as expected ?
Edit: Re-reading your question, it could be that your function is running before the page has finished loaded, and therefore won't execute properly; putting it in $(function) would indeed fix that!
The following is a jQuery function call:
$(...);
Which is the "jQuery function." $ is a function, and $(...) is you calling that function.
The first parameter you've supplied is the following:
function() {}
The parameter is a function that you specified, and the $ function will call the supplied method when the DOM finishes loading.
It's just shorthand for $(document).ready(), as in:
$(document).ready(function() {
YOUR_CODE_HERE
});
Sometimes you have to use it because your function is running before the DOM finishes loading.
Everything is explained here: http://docs.jquery.com/Tutorials:Introducing_$(document).ready()
Some Theory
$ is the name of a function like any other name you give to a function. Anyone can create a function in JavaScript and name it $ as shown below:
$ = function() {
alert('I am in the $ function');
}
JQuery is a very famous JavaScript library and they have decided to put their entire framework inside a function named jQuery. To make it easier for people to use the framework and reduce typing the whole word jQuery every single time they want to call the function, they have also created an alias for it. That alias is $. Therefore $ is the name of a function. Within the jQuery source code, you can see this yourself:
window.jQuery = window.$ = jQuery;
Answer To Your Question
So what is $(function() { });?
Now that you know that $ is the name of the function, if you are using the jQuery library, then you are calling the function named $ and passing the argument function() {} into it. The jQuery library will call the function at the appropriate time. When is the appropriate time? According to jQuery documentation, the appropriate time is once all the DOM elements of the page are ready to be used.
The other way to accomplish this is like this:
$(document).ready(function() { });
As you can see this is more verbose so people prefer $(function() { })
So the reason why some functions cannot be called, as you have noticed, is because those functions do not exist yet. In other words the DOM has not loaded yet. But if you put them inside the function you pass to $ as an argument, the DOM is loaded by then. And thus the function has been created and ready to be used.
Another way to interpret $(function() { }) is like this:
Hey $ or jQuery, can you please call this function I am passing as an argument once the DOM has loaded?
I think you may be confusing Javascript with jQuery methods. Vanilla or plain Javascript is something like:
function example() {
}
A function of that nature can be called at any time, anywhere.
jQuery (a library built on Javascript) has built in functions that generally required the DOM to be fully rendered before being called. The syntax for when this is completed is:
$(document).ready(function() {
});
So a jQuery function, which is prefixed with the $ or the word jQuery generally is called from within that method.
$(document).ready(function() {
// Assign all list items on the page to be the color red.
// This does not work until AFTER the entire DOM is "ready", hence the $(document).ready()
$('li').css('color', 'red');
});
The pseudo-code for that block is:
When the document object model $(document) is ready .ready(), call the following function function() { }. In that function, check for all <li>'s on the page $('li') and using the jQuery method .CSS() to set the CSS property "color" to the value "red" .css('color', 'red');
This is a shortcut for $(document).ready(), which is executed when the browser has finished loading the page (meaning here, "when the DOM is available"). See http://www.learningjquery.com/2006/09/introducing-document-ready. If you are trying to call example() before the browser has finished loading the page, it may not work.
I wondered what the difference of using jQuery or not using it might be considering the following task. I have not found any answer yet.
jQuery:
jQuery(function() { alert("Hello World!"); })
$(function() { alert("Hello World!"); })
Pure JavaScript:
(function() { alert("Hello World!"); })()
What is the difference? When should I use which approach? Thank you!
In general, $(function() { alert("Hello World!"); }) waits for $(document).ready() and the other function (an IIFE) fires immediately.
BUT the jQuery wrapped function is a very-specific use case (waiting for the DOM, using jQuery); your two examples are otherwise unrelated. Don't confuse them as 2 versions of the same thing.
$(function(){
alert("hello world");
});
is short hand for:
$(document).ready(function(){
alert("hello world");
});
so it will be executed after DOM loads.
while you pure js will be executed before DOM loads.
The jQuery version binds to be executed once the DOM loads. The kind in just a closure executes as soon as it's defined. So if you want it to execute immediately, use the second version, if it should wait until everything's loaded, use the first.
At least, that's what I've got off the top of my head.
The main difference is that the jQuery functions are executed after the DOM is loaded. And the pure JavaScript lambda function is executed immediately (within its context).
The second jQuery function is shorthand for the first.
You could still put the JavaScript lambda function inside the jQuery wrapper. This would mean that the lambda function would execute right after the DOM has loaded (thanks to jQuery taking care of that).
I have the following code:
File 1:
$(document).ready(function () {
addDataTableExts();
}
File 2:
function addDataTableExts() {
$.extend($.fn.dataTableExt.oStdClasses, {
sWrapper: 'no-margin last-child'
}
}
This seems to work okay. I now tried to replace this with the following:
File 2:
(function () {
$.extend($.fn.dataTableExt.oStdClasses, {
sWrapper: 'no-margin last-child'
}
}
This doesn't work.
Is there some reason why it only seems to work if I do this the first way? I thought
that by changing the first line of File 2 then it would cause the code to get
executed without me calling it.
You changed the code from running in the ready event to running immediately. It seems that you are loading your datatable plugin after loading file 2, so the plugin doesn't exist yet when you try to use it.
If you put it back in the ready event, it should work:
File 2:
$(document).ready(function () {
$.extend($.fn.dataTableExt.oStdClasses, {
sWrapper: 'no-margin last-child'
}
});
Note: Events in jQuery are not exclusive, so you can have several ready event handlers in the same page without problems.
"I thought that by changing the first line of File 2 then it would cause the code to get executed without me calling it."
If you actually changed only the first line as shown then you've created a syntax error - you've added an opening ( without a closing ). But simply adding the closing ) won't cause the now anonymous function expression to be executed. If you want the code to get executed without being called from File 1 you need to add extra parentheses () on the end to actually invoke the function.
Also you had a missing closing ) after the } at the end of $.extend(..., though that was also a problem in the first version of your code (and also a problem with the document ready handler in File 1).
(function () {
$.extend($.fn.dataTableExt.oStdClasses, {
sWrapper: 'no-margin last-child'
}); // <-- add missing ); here
})(); // <-- add missing )(); here
But you don't need the containing function at all unless it also wraps other code that you don't show, because that $.extend() statement on its on doesn't have any deleterious effect on the global scope.
Finally, if you do need to run that $.extend() after the page is ready but don't want to have a dependency between your two files you can add a document ready handler directly in File 2. Multiple document ready handlers will all be executed.
What is the difference between these two.
$(document).ready(function(){ ... });
(function(){ ... })();
Are these both functions called at the same time?
I know, document.ready will be triggered when the entire HTML page is rendered by the browser but what about 2nd function (self calling anonymous function). Does it wait for browser to complete rendering the page or it is called whenever it is encountered?
$(document).ready(function(){ ... }); or short $(function(){...});
This Function is called when the DOM is ready which means, you can start to query elements for instance. .ready() will use different ways on different browsers to make sure that the DOM really IS ready.
(function(){ ... })();
That is nothing else than a function that invokes itself as soon as possible when the browser is interpreting your ecma-/javascript. Therefor, its very unlikely that you can successfully act on DOM elements here.
(function(){...})(); will be executed as soon as it is encountered in the Javascript.
$(document).ready() will be executed once the document is loaded. $(function(){...}); is a shortcut for $(document).ready() and does the exact same thing.
The following code will be executed when the DOM (Document object model) is ready for JavaScript code to execute.
$(document).ready(function(){
// Write code here
});
The short hand for the above code is:
$(function(){
// write code here
});
The code shown below is a self-invoking anonymous JavaScript function, and will be executed as soon as
browser interprets it:
(function(){
//write code here
})(); // It is the parenthesis here that call the function.
The jQuery self-invoking function shown below, passes the global jQuery object as an argument
to function($). This enables $ to be used locally within the self-invoking function without needing
to traverse the global scope for a definition. jQuery is not the only library that makes use of $, so this
reduces potential naming conflicts.
(function($){
//some code
})(jQuery);
$(document).ready(function() { ... }); simply binds that function to the ready event of the document, so, as you said, when the document loads, the event triggers.
(function($) { ... })(jQuery); is actually a construct of Javascript, and all that piece of code does is pass the jQuery object into function($) as a parameter and runs the function, so inside that function, $ always refers to the jQuery object. This can help resolve namespacing conflicts, etc.
So #1 is executed when the document is loaded, while #2 is run immediately, with the jQuery object named $ as shorthand.
document.ready run after DOM is "constructed". Self-invoking functions runs instantly - if inserted into <head>, before DOM is constructed.
I have multiple document.ready functions on a page and I want a function to be called when all my document.ready functions have been executed. I simply want the function to be called
at the very end, after all other document.ready functions have executed.
An example of this could be that each document.ready function increments a global variable when it has been executed, and the last function needs to check the value of that variable at the very end.
Any ideas ?
This will be enough:
$(function () {
window.setTimeout(function () {
// your stuff here
}, 0);
});
This postpones the execution of your function after all other in the document ready queue are executed.
First idea (for small apps): Tidy up
You can just put everything in one $().ready() call. It might nieed refactoring, but it's the right thing to do in most cases.
Second idea: A Mediator [pattern]
Create a mediator class that will register functions and call its register() instead of $().ready(). When all functions are registered You just loop over the collection and run them in the single and only $().ready() and You have a point in code that is just after all is executed.
I am currently developing a kind of a framework for jquery applications that has a mediator. I might stick together a small version including the mediator if You're interested.
Why not just calling it after all the others ?
$(function(){
func1();
...
funcN();
functionThatNeedsToBeCalledAfter();
});
Of course you will have to cleanup your code to have only 1 place where the document ready function is used... but then your code would be more readable so it's worth it.
little hacky but might work, create a variable inside jquery scope like that
$.imDone = false
then create a function with setTimeout called after short time to lookup for the variable ser to true
var theLastFunctionToCall = function(){
alert('I m the last being called!')
}
var trigger = function(){
$.imDone?theLastFunctionToCall():window.setTimeout(trigger,10);
}
trigger();
I only recommend this when u have different $(document).ready in different big js files, but if you can refactor i sincerelly recommend an optimal solution.