jQuery document ready function

拟墨画扇 提交于 2019-11-27 15:03:25

Yes they're equivalent. See this link for reference .ready()

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.
});

$(function(){}) and $(document).ready(function() { }) are identical.

Imran Khan

Yes, this is identical. but the first one is usually used in jquery for easiness.

$(function() { 
    alert('test!'); 
});

The following code also working

$(document).ready(function(){
    alert("success");
});

OR

$(function(){
    alert("succes");
});

Yes:

$(document).ready(function() { 
  /* code */
});

…and:

$(function() { 
  /* code */
});

…are effectively the same, and the latter is commonly referred to as shorthand for the former.

If you're wondering why they produce the same outcome, it has to do with the jQuery constructor—the jQuery() function, aliased as $()and its allowed inputs.

The constructor is documented at api.jquery.com/jquery/, and its two relevant options are outlined below.


jQuery( selector [, context ] )

Accepts a string containing a CSS selector which is then used to match a set of elements.

Returns a jQuery object.

This option above is how you're invoking the jQuery constructor when writing:

$(document).ready(function() { /* code */ });

The document object is selected and used to construct a jQuery object. When the DOM is fully loaded, that jQuery object invokes the callback (the anonymous function) within ready().


jQuery( callback )

Binds a function to be executed when the DOM has finished loading.

Returns a jQuery object.

This option above is how you're invoking the jQuery constructor when writing:

$(function() { /* code */ });

The callback function (the anonymous function) is used to construct a jQuery object, and when the DOM is fully loaded, it is invoked.

Different ways to write jQuery Document Ready Snippet

$(document).ready(function() { ... }); 
$(function() { ... });
jQuery(document).ready(function() { ... });
jQuery(function() { ... });

http://webiwip.com/interview-questions-answers/jquery-interview-questions/10510

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!