Sourcing jQuery from a CDN? Sourcing jQuery from a CDN? javascript javascript

Sourcing jQuery from a CDN?


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.


@jrburke's answer does not work for me. According to the RequireJS api doc, you should not include the file extension in the path. So here is the working code:

requirejs.config({    paths: {        'jquery': 'https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min'    }});require(['jquery'], function($) {    //$ points to jQuery});

I have a working example on jsfiddle:http://jsfiddle.net/murrayju/FdKTn/


You can include it as a dependency for a module but it's a little flakey. e.g

define(["order!http://code.jquery.com/jquery-1.7.min.js"], function($) {})

It's not so good for 2 reasons

1) the jquery file itself isn't a module so the $ you get from the function won't be jquery

2) the order! plugin doesn't work well with CDN versions of scripts. See Requirejs' order does not work with priority config and CDN dependencies

I haven't had the chance to use this in a 'real' project yet because we haven't upgraded yet, but from my tests i've found that the best way is to include jquery in a script tag, then it works great as a dependency to your modules. Hopefully the following small sample will be helpful:

<html><head>    <title>Index2</title>    <script src="../../scripts/libraries/jquery.js" type="text/javascript"></script>    <script src="../../scripts/libraries/require.js" type="text/javascript"></script>    <script type="text/javascript"">        require(            {baseUrl: 'scripts'},             ['jquery'],             function (dollarSign) {                console.log(dollarSign('div').html('hi'));            });           </script></head><body>    <div>    </div></body></html>