In jQuery, how / why are these three ways to verify that the DOM is configured equivalently?

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

$(function(){});

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

I’m not sure that I fully understand what is happening in No. 2, and why this is equivalent to the standard ways of its implementation, No. 1.

+3
source share
2 answers

jQueryand $actually the same.

If you pass a function to a function $(), jQuery basically checks its type, and if it is a function, it will execute when the DOM is ready. This is just Javascript:

function myFunc(arg){
  if(typeof arg == 'function'){
    arg.call();
  }
}

From jQuery source:

// First, jQuery saves the old values of window.jQuery and window.$

// Map over jQuery in case of overwrite
_jQuery = window.jQuery,

// Map over the $ in case of overwrite
_$ = window.$,

...

// Later on, jQuery returns a reference to the actual jQuery object:
window.jQuery = window.$ = jQuery

...

// and if you use noConflict, it'll replace window.$ (and window.jQuery) with the old values again
noConflict: function( deep ) {
  window.$ = _$;

  if ( deep ) {
    window.jQuery = _jQuery;
  }

  return jQuery;
}

If you call the jQuery function, it checks the type of the argument:

init: function( selector, context ) {

  ...

  else if ( jQuery.isFunction( selector ) ) {
    return rootjQuery.ready( selector );
  }

Where rootjQuerycoincides withjQuery(document)

+7
source

The function passed as an argument to the jQuery constructor is bound to the document ready event.

0

Source: https://habr.com/ru/post/1770551/


All Articles