What's the difference between using (document).ready and jQuery(function ($)? [duplicate] - javascript

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
What is the difference between these jQuery ready functions?
I have always used:
$(document).ready(function (){
//Code goes here
});
And inserted my jQuery/JavaScript code therein (so that it waits on the html page to be fully loaded before running any code).
Lately, I have seen this:
jQuery(function($){
//Code goes here
});
I have searched for what the difference is here (mainly what the 'jQuery' part is all about).
My questions:
What does the jQuery part of the latter code block do, if anything?
What is the '($)' argument doing for that function?
Is there even a difference (other than making the page wait to be loaded) between my two code block examples?

The main difference is the closure around the $ variable. The first snippet assumes that the $ variable has not been released (by using .noConflict() or if another library you are using also makes use of $ but not as the jQuery variable).
The second implementation is safer because it doesn't make any assumptions but allows your internal code to safely use the $ variable by making it a parameter.

It is the same thing:
Using jQuery(function(){}) is just a shorthand for $(document).ready(function (){});
Note: you can use $ or jQuery

They're the same. From the documentation:
JQuery Call back (jQuery( callback ))
"This function behaves just like $(document).ready(), in that it should be used to wrap other $() operations on your page that depend on the DOM being ready. While this function is, technically, chainable, there really isn't much use for chaining against it."

They are nearly the same.
In the second function you are passing in jQuery i.e. $ into the function. $ is shorthand for the jQuery.
Straight from the jQuery library code for when you call $()
// tests to see if you passed in a function
} else if (jQuery.isFunction(selector)) {
// adds the function to be called when jQuery fires the ready event
return rootjQuery.ready(selector);
}
Comments are mine.

Related

JQuery 3.3.1 attr with 3 parameters. What it does?

I'm trying to update some old code someone left before, at some point, it made a call to the attr function of an old 3.3.1 JQuery like this:
$("#myiframe").attr("src", url, function () {
$(window).on("unload", function () {
// Some function stuff
});
});
My problem is than I want to know what exactly this does (I already know what attr does when it has 2 parameters, but not 3) before adapt it to a newer version, but when I search about the .attr function in JQuery, all I found is with only two parameters, not 3 like this, I don't know if is properly a callback function (unlikely, because none of the parameters this function accepts is a callback function), or other thing.
The JQuery file is the one served by googleapis, so is not likely it has been specially modified for this.
Please, can someone explain me what it does?
No signature of attr() accepts 3 arguments. The last argument is redundant. Even if it did serve a purpose, putting a window.unload event handler in there would not do anything useful.
Regards your comment under the question:
Why doesn't it launch a fatal error for the number of arguments?
It's because JS is a very permissive language. You can pass as many arguments to a function as you like, JS will ignore any extras and only bind those which you defined in the function definition (up to 2 in this case using attr()). Although note that it's still possible to retrieve all arguments that were used in the function invocation using the arguments keyword

wait for async javascript function to return

I am using a function supplied by a third party library. This function takes a callback function as a parameter, but I would like to wait for this callback to be called before continuing. Is there a standard / accepted way to do this?
I am not sure if this is a possible solution for you but you can achieve the desired result by breaking your code into 2 functions.
Suppose this is what you intend to do:
Basically this is your original function:
function origFunc() {
codeBeforeThirdPartyFunc();
ThirdPartyFunc(oldCallBackFunc);
Wait();
codeAfterCallBackFunc();
}
You can modify the code flow with something like:
function newFunc() {
codeBeforeThirdPartyFunc();
ThirdPartyFunc(newCallBackFunc);
}
function newCallBackFunc() {
oldCallBackFunc();
codeAfterCallBackFunc();
}
This will eliminate the wait loop. And as far as I know, busy waiting doesn't work in IE (because ? God only knows)..
Here's another method of loading jQuery asynchronously, which doesn't depend on another script.
I don't know if Sharad's solution would work in all cases (for instance if you function calls are so far chained that you have to pass data as variables instead of parameters). Same problem with global variables. JavaScript just doesn't have a "wait" ability.
Although I had a similar problem and with jQuery, I ended up with a MacGyver type solution that gives you tons of control on when javascript functions execute. I just posted it here as an answer to my own question (but I it's an answer that's not checked - look for my username Emile): How to get a variable returned across multiple functions - Javascript/jQuery

Javascript plugins design pattern like jQuery

Could someone write down a very simple basic example in javascript to conceptualize (and hopefully make me understand) how the jQuery plugin design pattern is done and how it works?
I'm not interested in how creating plugin for jQuery (so no jQuery code here at all).
I'm interested in a simple explanation (maybe with a bit of Javascript code) to explain how it is done the plugin concept.
Plz do not reply me to go and read jQuery code, I tried, but I it's too complex, otherwise I would have not post a question here.
Thanks!
jQuery has a library of functions stored in an internal object named fn. These are the ones that you can call on every jQuery object.
When you do $("div.someClass") you get a jQuery object containing all <div> elements of that class. Now you can do $("div.someClass").each( someFunction ) to apply someFunction to each of them. This means, that each() is one of the functions stored in fn (a built-in one in this case).
If you extend (add to) the internal fn object, then you automatically make available your custom function to the same syntax. Lets assume you have a function that logs all elements to the console, called log(). You could append this function to $.fn, and then use it as $("div.someClass").log().
Every function appended to the fn object will be called in such a way that inside the function body, the this keyword will point to the jQuery object you've used.
Common practice is to return this at the end of the custom function, so that method chaining does not break: $("div.someClass").log().each( someFunction ).
There are several ways to append functions to the $.fn object, some safer than others. A pretty safe one is to do:
jQuery.fn.extend({
foo: function() {
this.each( function() { console.log(this.tagName); } );
return this;
}
})
Tomalak already posted almost everything You need to know.
There is one last thing that helps jQuery do the trick with the this keyword.
it's amethod called apply()
var somefunction=function(){
alert(this.text);
}
var anObject={text:"hello"};
somefunction.apply(anObject);
//alert "hello" will happen
It really helps in creating abstractions so that framework/plugin users would just use this as intuition tells them, whatever there is inside Your code
It works, as many other js frameworks, using javascript prototype orientation.
For instance you can declare a simple function
var alertHelloWorld = function() {
alert('hello world');
}
And then tie it to an existing object (including DOM nodes)
document.doMyAlert = alertHelloWorld;
If you do this
document.doMyAlert();
The alertHelloWorld function will be executed
You can read more about javascript object prototyping here

How to make custom, no editing need, bulletproof jquery's noconflict version?

in my job i always have to use jquery with prototype can i make any custom jquery with library file like once i will add in head and then no need to change anything in any code.
is it possible?
I don't want to change anything in an code $ to jQuery.
from http://www.cssnewbie.com/runing-jquery-with-other-frameworks-via-noconflict/
Keeping it Short
The noConflict mode does have one other bit of functionality that I’ve found useful in some of my projects: you can select a different variable to use instead of the standard “jQuery”. The usage looks like this:
var $j = jQuery.noConflict();
Now in addition to using the default jQuery() notation, I can also use the shorter $j() notation. This allows me to avoid running into problems with other frameworks, while still enjoying almost the same conciseness in my code.
This just begs the question why dont you simply implement all your stuff in Prototype then - or implement everything in jQuery. Overall they both have the same capabilities.
However to directly answer your question - ther isnt really a way to make a custom build of jQuery. But you could simply put your noConflict call immediately following your inclusion of the jQuery library.
Then for your stuff you can simply wrap it all in
(function($){
// your jQuery code here... Can be used with $ as normal.
})(jQuery);
within that function youll be able to use $ as the alias - outside of it you would need to use jQuery. The only gotcha here is that if you want a variable defined inside here to be global youll need to make it that way manually as everything within this will be scoped to the function. You can do this like so:
(function($){
window.myGlobalVar = 'This is a global variable';
})(jQuery);
The best thing is often to wrap the $ in a private scope:
(function($) {
// jQuery stuff
})(jQuery)
You can also call the jQuery.noConflict() function before the wrap: http://api.jquery.com/jQuery.noConflict/
Another clean option is chaining the noConflict() into a domReady callback:
jQuery.noConflict()(function($){
// code using jQuery or $
});
console.log(typeof $ === 'undefined') // prints true
To address your question of whether you can have an "include-once" file, yes, you could do something similar to:
/* MyLibLoader.js */
document.write("<script type='text/javascript' src='prototype.js'></script>");
document.write("<script type='text/javascript' src='jquery.js'></script>");
window.$j = jQuery.noConflict();
And then in HTML
<head>
<script type='text/javascript' src='MyLibLoader.js'></script>
</head>
But this approach assumes you're happy to change your jQuery usage to $j

Unify $ function of Prototype and JQuery

Is there any JavaScript function that can unify $ function from both Prototype and jQuery?
Yes, this is the real use case I am facing now. I find $ function in Prototype and $ in jQuery is conflicting each other. I know that we could us jQuery.noConflict() to ressign $ back to Prototype, however by doing so, I will have to rewrite jquery-specific javacript code that use that $ function, or have jquery specific in a code block (eg. anonymous function).
Is there any easier way, without having to rewrite existing code in both library and have them in one page?
The code that could answer this question may look like this, and your feedback is greatly appreciated:
<script type="text/javascript" src="/path/to/prototype.js"></script>
<script type="text/javascript" src="/path/to/jquery.js"></script>
<script type="text/javascript">
/* <![CDATA[ */
var $j = jQuery.noConflict();
var $p = $; // reference to prototype's $
var $ = function(E, F){
var isJQuery = true;
//TODO: logic to determine which $ to use here YOUR SUGGESTION HERE ;-)
var result = null;
if(isJQuery){
result = $j(E, F);
} else { // prototype
//TODO: code to delegate prototype $
}
return result;
}
/* ]]>*/
</script>
// ... any existing javacode jQuery and Prototype using $ function.
Thanks.
update: Rewrite question to be more clear.
Well, first of all, I can rarely find usefull cases where both of the libraries have to be included in the same page. So you might consider to remove one.
I guess that this is due to a plug-in use, but have a look at the opponent plug-in list, I'm quite sure that there is an alternative.
Second, for your jQuery specific code, it's quite easy to rewrite it, using the anonymous function trick:
(function($){
... your code here ...
})(jQuery);
This will work in most of the cases where you don't put global variables or methods rather than binding them to events.
I've always got into the habit of putting all my jQuery code into a function, similar to gizmo's example:
jQuery(function($) {
// jQuery code here, using $
});
this is the same as the document.ready event handler.
jQuery's been great about making sure they play well with Prototype. Check this page for details, Avoiding Conflicts with Other Libraries.
I've seen both libraries used in the same pages before and it is generally because of third-party apps that are in your pages that use one library while your pages use the other. However, if you're doing all the development yourself, I suggest sticking with one or the other.

Categories