Reputation:
Here is how I would do it using plain HTML script tags per this SO Question on CDN suggestions. This would be a serial load (underscore->jquery->backbone) that holds up the rest of the page.
<script src="//cdnjs.cloudflare.com/ajax/libs/underscore.js/1.4.4/underscore-min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/backbone.js/0.9.10/backbone-min.js"></script>
How would I load these libraries using require.js or a similar non-blocking method?
References ( links to the API )
Upvotes: 2
Views: 357
Reputation: 18923
jquery is AMD Friendly so you can just require it in your require.js config
Backbone and underscore are no longer AMD Friendly so you have these options:
You can either include them as "externals", with shim assigning the correct dependencies (see here the docs and a tutorial )
Or you can use slightly altered versions of both libraries that are AMD enabled. You can find them in this repository.
Use an older version of backbone and underscore. (not recommended)
Note: If you opt for the shimming route, keep in mind that those libraries will not be load asynchronously.
Here's a working example using the ALTERED VERSIONS of the library:
require.config({
enforceDefine: true, //Only libraries AMD Friendly will be loaded
urlArgs: "bust=" + (new Date()).getTime(), //for development, forces browser to clear the cache
paths: { // relative paths (to the current file main.js)
"es5": 'libs/es5-shim/es5-shim',
"jquery": 'libs/jquery/jquery',
"jqueryThreeDots": 'libs/jquery/plugins/jquery.ThreeDots',//A jquery plugin
"underscore": 'libs/underscore/underscore.amd',
"underscore.string": 'libs/underscore/underscore.string',
"backbone": 'libs/backbone/backbone.amd',
"text": 'text',
"mediator": 'libs/backbone/plugins/backbone.mediator',
"bootstrap": 'libs/bootstrap/bootstrap.min',
"rangy": 'libs/rangy/rangy-core.amd',
},
shim: {
"bootstrap": {
deps: ["jquery"],
exports: "$.fn.popover"
}
}
});
An example with shim:
require.config({
enforceDefine: true,
urlArgs: "bust=" + (new Date()).getTime(),
paths: {
"jquery": 'http://code.jquery.com/jquery-1.9.1.min.js'
},
shim: {
backbone: {
deps: ["underscore", "jquery"], // Backbone dependencies
exports: "Backbone" // variable exported
},
underscore: {
exports: "_"
}
}
});
Upvotes: 3
Reputation: 5197
This is how we include jQuery, Underscore and Backbone with Require in our projects:
requirejs.config({
baseUrl: "js",
paths: {
backbone: "backbone-min",
jquery: "jquery.min",
underscore: "underscore-min"
},
shim: {
backbone: { deps: ["underscore", "jquery"], exports: "Backbone" },
jquery: { exports: "jQuery" },
underscore: { exports: "_" }
}
});
requirejs(["backbone"], function (Backbone) {
// Now we can reference not just Backbone but also jQuery and
// underscore since those two are dependencies for Backbone.
});
Upvotes: 1