Sourcing jQuery from a CDN?

wilsonpage picture wilsonpage · Nov 9, 2011 · Viewed 10.4k times · Source

I am using require JS and want to know the best method to use a CDN version of jQuery. I hear the 1.7 version is "AMD" which is supposed to help but can't find a straight example. Hope some RequireJS gurus can help me out.

Answer

jrburke picture jrburke · Nov 11, 2011

jQuery 1.7 registers itself as an AMD module by the name of 'jquery', so you need to create a mapping for 'jquery' using the paths config:

requirejs.config({
  paths: {
    'jquery' : 'https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min'
  }
});

require(['jquery'], function($) {
  //$ points to jQuery
});

Note however that RequireJS loads modules asynchronously and out of order, so if you have jQuery plugins you want to use that are not wrapped in define(['jquery'], function ($){ /* plugin code goes here */ }); calls, the plugin could execute before jQuery is loaded.

See the require-jquery project's README on ways to deal with files that depend on jQuery but do not wrap themselves in define() calls.