Are these both the same thing, i.e. ways of saying document ready:
$(function() {
//
});
and
$(function($) {
//
})(jQuery);
or is there a difference between the two, if so then when should I use which?
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.
jQuery $(document). ready() Equivalent in JavaScript This event fires when the initial HTML document has been completely loaded and parsed, without waiting for stylesheets, images, and subframes to finish loading.
$( document ). ready() ready() will only run once the page Document Object Model (DOM) is ready for JavaScript code to execute. Code included inside $( window ). on( "load", function() { ... }) will run once the entire page (images or iframes), not just the DOM, is ready. // A $( document ).
There is no difference in functionality between your examples - they both bind to DOM ready. For reference, there are two points at which you can bind your jQuery code. The first will execute when the DOM is ready (both are equivalent): // full example $(document).
The first one is a shortcut for .ready()
.
The second one is simply invalid as you're trying to call a non-callable object.
You probably meant this:
// v--------no $ at the beginning
(function( $ ) {
// simply a new lexical environment with a
// local $ parameter pointing to jQuery
})(jQuery);
...though it has nothing to do with DOM ready.
There is a variation on your first example that combines the two:
jQuery(function( $ ) {
// DOM ready, and creates a local $ parameter pointing to jQuery
});
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