$(document).ready(function() VS $(function(){ [duplicate] - javascript

This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
what is difference of $(function(){ }); and $(document).ready(function() { }) ;?
What are the differences between $(document).ready(function(){}) vs $(function(){})
and should I write it in the $ form or the new jQuery(document).ready(function(){ }) way?
If I have google api loaded is google.setOnLoadCallback(function() { a better way? or is it the same thing?
I've also seen people use $(function($){})
Can somebody help me, I'm lost. I bugs me when I don't know the code I write. I guess I should read through the library. Are the all being defined as the same thing?

The two ways are equivalent, I personally prefer the second, $(function() {}); it's just a shortcut for document ready.
About the new jQuery(document)... construct, you don't really need to use the new operator, jQuery will use it internally if you don't.
The argument that the ready handler function receives, is the jQuery object itself.
That's quite useful where you have to run jQuery in compatibility mode with other libraries, for example:
jQuery(function ($) {
// use $ here
});
The $ argument inside the callback will refer to the jQuery object, outside that function it might refer to another library like PrototypeJS.

$(document).ready(function() {});
$(function() {});
The two statements are actually the exact same. So the second call is just a shortcut for the first.
The $ notation is again only a shortcut for jQuery. If you have loaded jQuery into your website you can use both. Especially if you don't load other JS librarys, which maybe also use the $ sign. That brings us to your mentioned
(function($){
}(jQuery));
call. What is done here is to make sure, that within your created function expression the $ sign references to the jQuery object. You're calling that anonymous function (which has $ as parameter) and pass the jQuery object in.

I encourage to read some articles that are very useful to understand somethings in jQuery ( and of course in javascript ), this articles explain how to create a jQuery plugin, but reading it you will understand some basic and important things, like closures witch is the meaning in this (function($){}(jQuery)); statement.
http://www.authenticsociety.com/blog/jQueryPluginTutorial_Beginner

Related

Can we replace $ in prototype.js with some thing else like $p or $proto

I am using jquery and prototype.js. There is conflict in $.It could be resolved by using var $j = jQuery.noConflict(), but i have a plenty of file that are using $ for jquery so that would not be easy to remove. even i am using some plugings that also needs to be rename.(like jquery.dataTables.bootstrap.js in which i have to change from $ to $j)
So my question is can we rename $ in prototype.js to something else, so it will be easy.I am using prototype of version 1.5.1.
Thanks
Simple answer, no - the some of the PrototypeJS modules (Array, Enumerable, RegExp, String, etc) depend on the $() function being available, and expect it to return an extended element instead of a jQuery collection.
However you can wrap the jQuery code in a immediately executed function to work around your problem.
for example
(function($){
//jQuery code in here that uses $()
})(jQuery);
This is basically a Javascript closure that renames the jQuery() method to $() inside that context
changing $ to $p causing some problem(like calling jquery hide or show function, prototype.js function gets called). So i what did to solve the conflict is to open a prototype.js related things in new tab and using jquery.noConflict().

Why sometimes in Javascript there is the dollar sign ($arg) before function argument?

I see sometimes js snippets that are using the $ in front of the argument ($argName).
function someName(arg) {
// some code
// using arg
}
function someName($arg) {
// some code
// using $arg
}
In this js example it works either way with or without the $ in front of the arguments. Can anyone explaine if it has any use?
The $ character is legal in JS identifiers, and is often used simply as a code convention to indicate that the passed parameter is already a jQuery object (as opposed to a native DOM element).
This serves as a reminder that it's not necessary to re-invoke the jQuery $(param) wrapper function on that parameter.
It's also used quite a lot in Angular JS code.
It's sometimes used to reference an object from another library , like JQuery or AngularJS , what you're talking about here looks like AngularJs's dependency injection to me
UPDATE
See this answer it might be useful

Why is jQuery syntax so strange - how does it even get parsed? [duplicate]

This question already has answers here:
How is jQuery's $ a function and an object?
(8 answers)
Closed 8 years ago.
I'm trying to understand jQuery, but I'm hindered by the syntax looking so strange to me. I don't even understand how a regular JavaScript parser parses it! I can read sample code and I'll understand from the accompanying material what it's doing, but I don't understand how.
I understand that $ is just an alias for jQuery, but that doesn't answer the question. Take the classic jQuery function used to delay things until the page is fully loaded:
$(document).ready(function() {
...
});
or a jQuery selector that selects all p elements in the DOM and applies a CSS rule:
$('p').css('color', 'blue');
So... somehow document and 'p' are recognized as keys, and associated with the appropriate values, right? Except that doesn't seem like it could be true, because then jQuery would have to pre-calculate the results it was going to return for any possible key it could be asked for, including element ids that jQuery probably couldn't know about! So how on earth does it really work?
(edited to fix an error in describing code)
The answer is simpler than you think. The $ is indeed an alias for the jQuery library... which is implemented as a single function. When you see code that looks like this:
$(document).ready(function() {
...
});
What you are seeing is:
The jQuery function ($) being called...
... with the argument document ...
... which returns an object ...
... which has a ready method, that gets called ...
... with an anonymous function for its argument.
I had trouble with this when I first ran into it. I knew that in JavaScript, functions are first-class objects (which is why you can pass one as an argument) but somehow, that didn't make clear to me that something which was clearly a large, sophisticated object (i.e., the jQuery library) might also be a function.
In fact, it's both. It's a function, and it's also an object that has its own properties, which include functions. That's why sometimes you'll see code like the following:
$.getJSON('http://www.foo.com/search?q=....
In our previous code, $ was the function we were calling. In this code, $ is the object on which the function we are calling, getJSON, is located.

What exactly does !function ($){...}(window.jQuery) do?

I'd like to know exactly what's going on here. I know what $(document).ready(function() {...}); does and when it comes into effect. Same goes for jQuery(function($) {...}.
But what does this do?
!function ($) {
$(function(){
var $window = $(window)
//normal jquery stuff
})
}(window.jQuery)
Is it loaded when jQuery is loaded instead of when the document is 'ready'?
It creates a closure in which the variable $ is assigned the value of window.jQuery.
The intention is to allow the uninformatively named variable $ to be used as a shortcut for jQuery without conflicting with the large number of other libraries and custom functions that also use $ as a variable name.
Using the ! operator before the function causes it to be treated as an expression
!function () {}()
The syntax you're looking at is used for setting up a jQuery closure. This is used to ensure that the jQuery $ variable is garuanteed to be available and correct within the code; ie it can't be overwritten in the global scope by anything else (which is possible if you're using multiple libraries, etc).
This technique is often used by jQuery plugin authors -- if you're interested in finding out more, the docs are here, and explain in more detail why you'd want to wrap your jQuery code in a function like this.
The only point of interest that's different in your example is that in the docs, the function is wrapped in brackets, whereas in the example you've given it's preceded by a !
The ! is a not operator, but doesn't actually get used for anything; I think it's just there instead of the brackets to save a single character of code. Probably helpful if you're into minifying javascript.
Not quite sure but I guess this is somewhat equivalent to (function(){})() approach and it's about js closures. And it ensures $ and jQuery are the same thing
The '!' is a 'not' operator. It doesn't do anything in the code. The only reason it is there is to signify that the function will execute immediately.
You may also see functions wrapped in parenthesis instead.
(function() {}());
Whatever is used is personal preference.

Please explain these lines in the jQuery-ui project - has to do with adding "sub-plugins"

Lines 10 - 16 of jquery.effects.core.js:
;jQuery.effects || (function($, undefined) {
var backCompat = $.uiBackCompat !== false; // Irrelevant
$.effects = {
effect: {}
};
})(jQuery); // At end of file
As I understand it, this adds an effects "namespace", but only if it doesn't already exist.
Can someone explain to me:
What is the initial semi-colon for?
What is the purpose of the undefined parameter? Is the meaning of undefined overridden in some way?
What's the difference between adding a function directly to the jQuery object, and adding one to jQuery.fn as recommended in the jQuery documentation?
Finally, if I wanted to create a bunch of jQuery plugins that would only be used by my own team, would it make sense to lump them all under a company namespace using something like the code above?
Edit: I realize now jQuery.effects is probably a bad example. I see jQuery.ui.core.js does it differently:
(function( $, undefined ) {
$.ui = $.ui || {};
// add some stuff to $.ui here
$.fn.extend({
// plugins go here
});
})(jQuery);
But what is the use of the ui object if plugins are added directly to $.fn anyway? Could I define my namespace under $.fn and add all my plugins to $.fn.acme, so that I use them like so: $('something').acme.doStuff()?
Is there a best practice for this sort of thing?
It checks if jQuery.effects exists
If not, it defines a function and calls in the same time
(function() { ... } (jquery), it passes jQuery object for reasons related to scope and conflict and such.
The first line in that function is said to be irrelevant, it seems to be checking a presence of a jQuery plugin property
It defines a placeholder (like namespace or container class) for the effects jQuery plugin property.
So, to your questions:
1 . What is the initial semi-colon for?
I think nothing special. Just ensuring clean statement. This has some edge cases if the last line before this one was a function declaration close.
2 . What is the purpose of the undefined parameter? Is the meaning of undefined overridden in some way?
It just ensures this doesn't happen later. Passes the global object directly. Common pattern I think.
3 . What's the difference between adding a function directly to the jQuery object, and adding one to jQuery.fn as recommended in the jQuery documentation?
It's the way jQuery is structured and general organization issue. The jQuery object is a function and returns an object. The .fn handles registering this one to apply on returned jQuery objects (from jQuery select or so), so, that's better so that jQuery actually knows about your added function.
4 . Finally, if I wanted to create a bunch of jQuery plugins that would only be used by my own team, would it make sense to lump them all under a company namespace using something like the code above?
Most people don't do it. Wouldn't recommend it. Maybe a common "small" prefix is enough.

Categories

Resources