I've seen four different ways to tell jQuery to execute a function when the document is ready. Are these all equivalent?
$(document).ready(function () {
alert('$(document).ready()');
});
$().ready(function () {
alert('$().ready()');
});
$(function () {
alert('$()');
});
jQuery(function ($) {
alert('jQuery()');
});
ready() method offers a way to run JavaScript code as soon as the page's Document Object Model (DOM) becomes safe to manipulate. This will often be a good time to perform tasks that are needed before the user views or interacts with the page, for example to add event handlers and initialize plugins.
ready() and $(window). load() event is that the code included inside onload function will run once the entire page(images, iframes, stylesheets,etc) are loaded whereas the $(document). ready() event fires before all images,iframes etc.
We can have multiple document. ready() function in our code but only one body. onload() is allowed.
jQuery ready() Method The ready event occurs when the DOM (document object model) has been loaded. Because this event occurs after the document is ready, it is a good place to have all other jQuery events and functions. Like in the example above. The ready() method specifies what happens when a ready event occurs.
There is no difference.
$
is the same as jQuery
. If you view the unminified source, you will see var $ = jQuery = ...
or something to that effect.
The jQuery
function checks the type of it's parameter, if it is a function, it treats it the same as $(document).ready(...)
Calling jQuery
without a parameter defaults to using document
. So $()
and $(document)
are identical. Try it in Firebug.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With