Are the end results of the following jQuery snippets identical?
Snippet 1:
$(function() { alert('test!'); });
Snippet 2:
$(document).ready(function() { alert('test!'); });
In other words, is $(function(){})
just shorthand for $(document).ready(function() { });
?
The reason I'm asking is because we're seeing some strange issues with a small application we've built using jQuery and jQuery UI. Occasionally, when performing a form submit action by clicking a button the browser window will just freeze. We can still use the underlying browser window (the one that launches the pop-up) until we perform some actions there. The users can only continue by force closing the browser (Internet Explorer, obviously). We suspect this is related to the Acrobat PDF plug-in, but I'm just checking all the angles here, because I found this issue which seems to exhibit similar behaviour.
jQuery ready() MethodThe 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.
The ready() method is used to make a function available after the document is loaded. Whatever code you write inside the $(document ). ready() method will run once the page DOM is ready to execute JavaScript code.
ready() function will load as soon as the DOM is loaded and before the page contents are loaded. You should wrap all your javascript code with this function to ensure that the code only runs when the page is fully rendered.
So technically it doesn't matter where you put it. Many people like putting script in the head, because it makes sure the script is read before the page is loaded. Other people like putting it at the very end (just before the end body tag) so that all of the elements of the page are loaded before the script reads them.
All three of the following syntaxes are equivalent:
$(document).ready(handler)
$().ready(handler) (this is not recommended)
$(handler)
Aliasing the jQuery Namespace
When using another JavaScript library, we may wish to call $.noConflict() to avoid namespace difficulties. When this function is called, the $ shortcut is no longer available, forcing us to write jQuery each time we would normally write $. However, the handler passed to the .ready() method can take an argument, which is passed the global jQuery object. This means we can rename the object within the context of our .ready() handler without affecting other code:
jQuery(document).ready(function($) {
// Code using $ as usual goes here.
});
Yes they're equivalent. See this link for reference .ready()
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