I'm working with a script and have found the following, which I really can't find any info of what it means
(function($) {
$(document).ready(function(e) {
... bla bla bla ...
});
}) (jQuery);
Is (function($){}) (jQuery); the same as $(function () {}); ? and if so, why would somebody define twice document.ready ?
No, it's not the same. It's an anonymous function which is being passed the jQuery object, to insure that it is available as the local variable $ within the scope of the function, even if the global variable $ is overwritten by another library. It is completely different than $(function () { }) and $(document).ready(function () { }).
This particular pattern is recommended in the jQuery plugin authoring documentation:
[When authoring a plugin] it's a best practice to pass jQuery to an IIFE (Immediately Invoked Function Expression) that maps it to the dollar sign so it can't be overwritten by another library in the scope of its execution.
(function( $ ) {
$.fn.myPlugin = function() {
// Do your awesome plugin stuff here
};
})( jQuery );
Is (function($){}) (jQuery); the same as $(function () {}); ?
No. The first is immediate invocation of an anonymous function, used primarily for preventing pollution of the global scope. In this case, it's also used to make sure that $ is a reference to jQuery, without worrying about overwriting $ elsewhere.
The second is the shorthand for binding a document ready handler with jQuery.
More reading:
What is the purpose of a self executing function in javascript?
What is the reason for this JavaScript immediate invocation pattern?
No it isn't, (function($){}) (jQuery); is an IIFE(Immediately invoked function expression) passing jQuery as a parameter and using $ to represent it in the function scope so that no conflicts will occur if another library that uses $ is loaded without using jQuery.noConflict.
Nope
(function(){})();
is executed as soon as the browser encounters that script.
.ready() is an event that is triggered after the entire document is parsed
No it's not. It is a closure with a document ready handler inside it. It is used to ensure that the $ within the enclosure is reserved for jQuery and does not interfere with any other library.
A nice clear explanation here;
http://jquery-howto.blogspot.com/2008/12/what-heck-is-function-jquery.html
Related
What is the difference between function($) and $(function())?
Is this code redundant?
(function($) {
"use strict";
$(function() {
run_code();
});
})(jQuery);
Are they both document ready functions?
They may look similar, but they are completely unrelated.
This is called an Immediately Invoked Function Expression (IIFE). These are not specific to jQuery, but in this case, it ensures that within the body of this function, $ will refer to jQuery, even if something outside the function has overwritten the global $ variable with something else. It is a defensive practice for minimizing conflicts with other libraries.
An additional benefit is that any variables declared within this function will not be added to the global scope. Even without jQuery, this is a common practice used to help modularize code and avoid polluting the global scope.
(function($) {
"use strict";
})(jQuery);
This tells jQuery to execute the specified function when the DOM is "ready":
$(function() {
run_code();
});
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...
Im creating a theme for wordpress and I need to use some jQuery. Ive found bits of code online and ive made a few bits myself. However, when using jQuery provided by wordpress it is in noConflict mode and instead of using $ it is set to "jQuery". That is fine but I dont want to have to modify all my code and any code I find online to use "jQuery" instead of $.
So it tells me that by placeing function ($) at the end you are able to use the $ as the jQuery alias, but only in that functions scope. That is fine, but I was hoping that it would work and pass through to the functions I call from inside that scope. That is where my problem is. How can I make the jQuery code that uses $ inside my "resizeandcenter" function work.
jQuery('.artworklist > li > a > img').load(function ($){
resizeitems('artworklist');
});
This is my function that I want to be able to use the $ inside as I dont want to have to modify all my code / and any code I find online.
function resizeitems(elementname){
//Do some jquery stuff using $
}
Perhaps there is an alternative way to do what I am doing or I am doing it wrong?
EDIT:
My function "resizeitems" is on its own in a js file thats included in my page header.
The other code, the jQuery code in my first code block is at the bottom of the page in a script block.
So im a bit unsure about the answer saying to wrap my function?
You can wrap your entire code in a self executing closure (or an on ready/load closure) like this
(function ($) {
// do your stuff here
}(jQuery));
Then you can use $ within that closure
Here is an example on jsfiddle for you
window.addEventListener("load", function () {
(function ($jq) {
$jq("body").append($jq("<div>").text("hello"));
}(jQuery));
}, false);
Here is an example using jquery's ready event listener
jQuery(document).ready(function() {
(function ($jq) {
$jq("body").append($jq("<div>").text("hello"));
}(jQuery));
});
On jsfiddle
Or a further alternative in jquery, mostly syntax change, as suggested by #Mathletics
jQuery(function($jq) {
$jq("body").append($jq("<div>").text("hello"));
});
On jsfiddle
You need to pass jQuery into the top-level closure containing your code. Usually this is inside the $(document).ready() call. A basic example looks like this:
jQuery(function($) {
function resizeitems(elementname){
//Do some jquery stuff using $
}
$('.artworklist > li > a > img').load(function (){
resizeitems('artworklist');
});
});
jQuery is now aliased to $ inside of that closure.
All what matter is scope here. If your other functions are in some other scope you can just remap global jQuery to $ in that scope, so that you don't have to change the code.
var $ = jQuery;
You can even set it in global scope, but you may affect other usage of $ on the page if it was used for something else:
window.$ = jQuery;
I am studying Backbone and the todo example apps from http://todomvc.com/
I have noticed there are 3 severals ways of starting the code in the files:
$(function() {
// code here
});
$(function( $ ) {
// code here
});
(function() {
// code here
}());
I do not understand the differences and when I should use one over the other.
I also saw some people using this to start their code:
$(document).ready(function(){
// code here
});
From what I have seen, this is the full way of writing it right?
In a more general way, should I always include my javascript code into something like that in each files?
Thanks for your advice.
$(document).ready(function(){}) ensures that your code runs on DOM ready, so that you have access to the DOM. You can read more about this in jQuery's documentation.
$(function(){}) is just an alias to #1. Any code in here will wait for DOM ready (see the docs).
$(function($){}) is equivalent to #1 and #2, only you get a clean reference to jQuery in the local scope (see the note below). You can likewise pass in $ to the function in #1, and it'll do the same thing (create a local reference to jQuery).
(function(){}()) is just a self-executing-anonymous-function, used to create a new closure.
Please note that none of these are specific to Backbone. The first 3 are specific to jQuery, while #4 is just vanilla JavaScript.
Note: To understand what's going on in #3 above, remember that $ is an alias to jQuery. However, jQuery is not the only library that uses the $ variable. Since the $ might be overwritten by someone else, you want to ensure that within your scope, $ will always reference jQuery - hence the $ argument.
In the end, it basically boils down to the following 2 options:
If your JavaScript is loaded in the head, you have to wait for document ready, so use this:
jQuery(function($) {
// Your code goes here.
// Use the $ in peace...
});
If you load your JavaScript at the bottom of your document (before the closing body tag - which you should definitely be doing), then there's no need to wait for document ready (since the DOM is already constructed by the time the parser gets to your script), and a SEAF (A.K.A. IIFE) will suffice:
(function($) {
// Use the $ in peace...
}(jQuery));
P.S. For a good understanding of Closures and Scope, see JS101: A Brief Lesson on Scope.
I guess it makes sense to start out, by realizing that $ = jQuery. The purpose of which down below when reading about namespaces within anonymous functions will make more sense. But in essence, you can use either of them. One would use jQuery() instead of $() if they were using multiple libraries, and wanted the $ to be used by the other one.
$(document).ready(function(){
// Here we have jQuery(document) firing off the ready event
// which executes once the DOM has been created in
// order to ensure that elements you are trying to manipulate exist.
});
$(function () {
// Short-hand version of $(document).ready(function () { });
});
More information on Document.ready()
Putting the $ within the parenthesis ensures the jQuery $ alias (you can be safe it always signifies jQuery this way).
$(function ($) { /* code here : $ always means jQuery now */ });
Lastly you have an IIFE (Immidiately-Invoked Function Expression)
- IIFE explanation
(function (myNameSpace, $) {
// This is an anonymous function - it is ran instantly
// Usually used for namespaces / etc
// This creates a scope/wrapper/closure around everything inside of it
}(window.myNameSpace, jQuery));
The $ at the top (with it's matching jQuery on the bottom) signify that the
$ (dollar sign) stands for jQuery within the scope of the namepsace.
This is done to ensure that other libraries do not collide with what the developer
intends/wants the $ to be used with.
(function (myNameSpace, $) {
// Now because of all of this scope/wrapper/closure awesome...
// you can create -INTERNAL- variables (sort of like Private variables from other langs)
// this variable cannot be accessed outside the namespace unless it is returned / exposed
var internalVariable = '123'; // Internal
// Even Internal functions!
function privateFunction () {
console.log('this is private!');
}
// --------------------------------------------------------
// Public -method- of nameSpace exposing a private variable
// Notice we're using the myNameSpace object we exposed at the top/bottom
myNameSpace.nameSpaceMethod = function () {
privateFunction(); // we can call the private function only inside of the namespace
return internalVariable; // now we could get this variable
};
}(window.myNameSpace, jQuery)); // notice these mirror the above arguments in the anon function
More information on anonymous functions
Now if we're outside of the namespace, we can see how these internal/public methods and variables are effected:
// This will come up undefined
alert(internalVariable);
// This will trigger a -method- of the myNameSpace namespace - and alert "123"
// Showcasing how we access a Public method - which itself has access to the internal variable
// and exposes it to us!
alert(myNameSpace.nameSpaceMethod());
These two:
$(function() {
// code here
});
$(document).ready(function(){
// code here
});
Are directly equivalent, they are both the way to start some jQuery when the document has loaded. The former is just a shorter version of the latter.
This one:
(function() {
// code here
}());
is just a scoped function with zero parameters, which is immediately called with zero parameters.
jQuery(document).ready(function($){}); is a known and great way to protect the $ from causing errors.
What I'm curious about is if jQuery(window).load(function($){}); would work in the same way?
Basically, what I have now is:
jQuery(document).ready(function($){
$(window).load(function(){
// ...
});
});
This just seems unnecessary to me, any ideas about simplifying this? I need the safety of having jQuery properly mapped to $ (or whatever the correct term is) but the same timing as window.load()
I prefer this...
(function($){
$(window).load(function(){
//everything is loaded (images, scripts, etc.)
});
// and/or
$(document).ready(function(){
// the dom is in place, but everything is not necessarily loaded
});
})(jQuery);
Note: This will only work if jQuery was included before this script. I have never encountered any problems with jQuery being undefined this way. Furthermore, you will never have problems with $ being undefined, because you are passing it into your anonymous function.
You can do this:
(function($) {
$(window).load(function(){
// ...
});
})(jQuery);
The anonymous function will be executed immediately rather than waiting for DOM ready as in the code in the question. Within the function $ will be a reference to jQuery so won't clash with any other $ defined outside the anonymous function.
You can create a local parameter:
(function($) {
$(...)
})(jQuery);
This code executes an anonymous function with a parameter named $, passing jQuery as the parameter value.