0

I am reading some code which use requirejs to handle jquery.

It use

require([
'jquery',
], 

function(
$
){} );

I am wondering why just using $ is enough for all jquery functions?

5
  • Huh? What don't you understand? What would you expect? Commented Jul 7, 2013 at 2:53
  • You might be misunderstand that $ has lots of properties. Commented Jul 7, 2013 at 2:54
  • I am wondering jquery support Requrejs by default? Requirejs needs every module use define. Commented Jul 7, 2013 at 2:58
  • I think you are using require-jquery.js which has already defined jquery. Commented Jul 7, 2013 at 3:10
  • if you are using github.com/jrburke/require-jquery, take into account that is no longer recommended or mantained Commented Jul 7, 2013 at 3:14

2 Answers 2

1

jQuery will define jquery module by itself if define function has already defined.

The following code is in jquery.js.

if ( typeof module === "object" && module && typeof module.exports === "object" ) {
    // Expose jQuery as module.exports in loaders that implement the Node
    // module pattern (including browserify). Do not create the global, since
    // the user will be storing it themselves locally, and globals are frowned
    // upon in the Node module world.
    module.exports = jQuery;
} else {
    // Otherwise expose jQuery to the global object as usual
    window.jQuery = window.$ = jQuery;

    // Register as a named AMD module, since jQuery can be concatenated with other
    // files that may use define, but not via a proper concatenation script that
    // understands anonymous AMD modules. A named AMD is safest and most robust
    // way to register. Lowercase jquery is used because AMD module names are
    // derived from file names, and jQuery is normally delivered in a lowercase
    // file name. Do this after creating the global so that if an AMD module wants
    // to call noConflict to hide this version of jQuery, it will work.
    if ( typeof define === "function" && define.amd ) {
        define( "jquery", [], function () { return jQuery; } );
    }
}
Sign up to request clarification or add additional context in comments.

Comments

0

Take a look at How to use RequireJS with jQuery.

But yes, you only need $ (witch is the same as jQuery) because every method (or plugin) jQuery provides is encapsulated inside that variable.

If you are using requirejs to load your files and you don't do it that way, $ will be undefined.

Example from the site:

require(['jquery'], function( $ ) {
    console.log( $ ) // OK
});

require(['jquery'], function( jq ) {
    console.log( jq ) // OK
});

require(['jquery'], function( ) {
    console.log( $ ) // UNDEFINED!
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.