Is this redundant?
jQuery(document).ready(function($} {
//stuff
}(jQuery));
This is ugly and overly verbose:
(function($) { $(document).ready(function() {
//stuff
})})(jQuery);
What I need:
Efficient, pretty, and semantic.
Avoids namespace conflicts.
Minimal.
Just about the entire script runs after the dom is ready. Nesting .ready() in an anonymous function on different lines isn't ideal, because almost the whole file would end up being double tabbed.
What's the best way?
jQuery already passes a reference to itself to the ready callback, so just do
jQuery(document).ready(function ($) {
//stuff
});
// or shorter
jQuery(function ($) {
//stuff
});
Btw, this
jQuery(document).ready(function ($) {
//stuff
}(jQuery));
would even be wrong. It calls the anonymous function immediately, with jQuery as argument and then passes the return value to jQuery(document).ready().
regarding this:
(function($) { $(document).ready(function() {
//stuff
})})(jQuery);
this is basically wrapping the jQuery's version of document-ready function:
$(document).ready(function() {
//stuff
});
in an IIFE:
(function($) {
// on-ready-function
}(jQuery));
which might be useful if you need to additionally encapsulate variables, etc.
But I usually do this:
$(function() {
//stuff
});
and have not had any problems with this (in my 10 years career).
One thing to note is to always put scripts at the end of the body.
Related
I see
First
$(function() {
...
});
Second
(function() {
})();
Third
function() {
}
$(document).ready(function(){
});
Maybe there are more, what are the differences?
Your notation is mainly jQuery (atleast the ones with $)
This is shorthand for a DOM ready function, equivalent to the bottom one
This is a self executing function with the parameter specified in the trailing ()
This is a DOM ready function $(document).ready(function() {}); atleast, the function above it is simply a function.
so these indeed are a few different ways to execute javascript code, some of them are library dependent (using jQuery) others are done specifically because of differences in scope.
the first block:
$(function() {
...
});
is utilizing the js library jQuery that uses the namespace '$' what you are doing here is calling the jQuery '$' function passing in the first parameter of another anonymous function... this is a shorthand way to call $(document).ready(function(){});... both of those statements wait for the DOM to complete loading (via the onload event) before interpreting the javascript inside
the second block:
(function() {
})();
is a procedure called an (IIFE) Immediately-Invoked Function Expression... which in essense is defining an anonymous function and calling it immediately.
the third block:
function() {
}
$(document).ready(function(){
});
represents two things... the first function declared actually should have been named something like function myFunction(){...} and thus could be called later myFunction(parameters);
and finally $(document).ready(function(){}); is the javascript library jQuery's way of saying grab the 'document' element of the dom, and attach an event listen to it looking for the onload event, when that event is triggered execution the function passed as a parameter...
I already know about the advantages of wrapping your Javascript in a function like this:
(function () {
// code goes here
}())
But I've seen some scripts which accomplish this by passing the wrapper function to the jQuery object:
$(function () {
// blah blah blah blah blah
});
What's the advantage of doing it this way, or is it just a matter of personal taste? And does doing it the second way negate the need for $(document).ready()?
The first one
(function () {
// code goes here
}())
That is self executing function.
And the second function is jquery specific.
If you see the docs
The .ready() method can only be called on a jQuery object matching the current document, so the selector can be omitted.
The .ready() method is typically used with an anonymous function:
$(document).ready(function() {
// Handler for .ready() called.
});
Which is equivalent to calling:
$(function() {
// Handler for .ready() called.
});
Your first example is just standard JavaScript a self executing function, the second one is jQuery specific, and is a shortcut for $(document).ready(function () {});
see the jQuery documentation
and also this question for more info on self executing functions
(function(){}()) is an IIFE (Immediately-Invoked Function Expression) and is just an function executing Immediately
$(function(){}) is an jQuery callback fro when the browser is ready
i often have to add jQuery to sites that have mootools on them so to avoid $ conflicts i do somthing like this:
;(function($, app, undefined){
// code here
}(jQuery, myApp = window.myApp || {}))
I would like to ask on how I can use both functions once the page loads
jQuery(document).ready(function($)
{
$('#list').tableScroll({height:500});
});
and
jQuery(document).ready(function($)
{
$('#list').tableSorter();
});
jQuery(document).ready(function($) {
$('#list').tableSorter().tableScroll({height:500});
});
jQuery supports method chaining.
jQuery(document).ready(function($) {
$('#list')
.tableScroll({height:500})
.tableSorter();
});
jQuery(document).ready(function($)
{
$('#list').tableScroll({height:500});
$('#list').tableSorter();
});
Just put both under one DOM ready handler and use chaining:
$(document).ready(function() {
$("#list").tableScroll({ height: 500 }).tableSorter();
});
$(document).ready(function() {
$("#list").tableScroll({ height: 500 }).tableSorter();
});
I guess its fine to have more than one
jQuery(document).ready(function($) { .... }
both will be called on page on load body :). irrespective of no of call`s made, all will be called on page load only.
Simple, use
jQuery(document).ready(function() {
$('#list').tableScroll({height:500}).tableSorter();
});
There is a shorter version of jQuery(document).ready(function()) that you could use that would have the same result:
$(function() {
// code to execute when the DOM is ready
});
For this situation, using the elegant chaining:
$(function() {
$('#list').tableSorter().tableScroll({height:500});
});
For a discussion of the difference between these two approaches, see this very helpful question.
Here's how I would do it:
// Create an immediately-invoked function expression
(function ($) {
// Enable strict mode
"use strict";
// Cache the selector so the script
// only searches the DOM once
var myList = $('#list');
// Chain the methods together
myList.tableScroll({height:500}).tableSorter();
}(jQuery));
Writing your jQuery in an IIFE like this means you can run the code alongside other libraries that also use $, and you won’t get conflicts.
Be sure to include this JavaScript at the end of your document, just before the closing </body> tag.
If I make an AJAX request and want to call all functions that were set up by $(document).ready(). How can I do it? Thank you
$(document).ready();
If that doesn't work, try this:
function startup() {
// All your functions in here.
}
$(document).ready(startup);
And after your AJAX request is finished:
startup();
The easiest way is to use a shared function:
$(document).ready(function() {
setup();
});
$.post('/', {}, function() {
setup();
}, 'json');
But if you're using it to re-assign listeners, you would probably be able to get away with assigning them before they're created, like this:
$(document).ready(function() {
$(document).delegate('.my-button', 'click', function() { });
});
Using this code, all .my-button clicks will be handled by your custom function, regardless of whether the button existed in your DOM upon DOMReady.
Note that:
$(document).ready(function() { ... }); can be minimized to $(function() { ... });
If you're using jQuery 1.7+, prefer .on over .delegate: $(document).on('click', .my-button', function() { });
Prefer narrower context over broader, i.e. $('#close-parent').delegate over $(document).delegate
Instead of triggering document.ready by hand (which would be bad practice IMHO), make a function that's called setup which sets up all listeners etc. and invoke this function when you need to re-apply things etc.
Before I heard about self executing functions I always used to do this:
$(document).ready(function() {
doSomething();
});
function doSomething()
{
// blah
}
Would a self executing function have the same effect? will it run on dom ready?
(function doSomething($) {
// blah
})(jQuery);
Nope. A self executing function runs when the Javascript engine finds it.
However, if you put all of you code at the end of your document before the closing </body> tag (which is highly recommended), then you don't have to wait for DOM ready, as you're past that automatically.
If all you want is to scope your $ variable, and you don't want to move your code to the bottom of the page, you can use this:
jQuery(function($){
// The "$" variable is now scoped in here
// and will not be affected by any code
// overriding it outside of this function
});
It won't, it will be ran as soon as the JavaScript file is executed.
No, self-executing javascript functions run right there.
If you want to create a DOM ready function, write the following:
$(function() {
// this will run on DOM ready
});
Which is a shorthand of:
$(document).ready(function() {
});
No, the self-executing function run immediatly after you "declare" it on your code. Even if it's located on an external .js file.
In your example, there is a possibility that your function will execute and the value of jQuery is undefined. If you want your code to be executed on DOMReady, continue using
$(document).ready(function(){
doSomething();
});
or
$(function(){
doSomething();
});
or even
window.onload = function(){
doSomething();
}
$(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(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.
jQuery document.ready vs self calling anonymous function