Reputation: 1066
I'm using RequireJS to declare dependencies I need in my project. I've configured RequireJS so that jQuery is loaded. However, for some reason, the browser gives errors that jQuery is not defined (Bootstrap.js needs jQuery).
<script type="text/javascript" src="./modules/requirejs/require.js" data-main="./js/main.js"></script>
<script src="js/bootstrap.js"></script>
Is it because requireJS loads the dependencies asynchronously, so it might actually happen AFTER bootstrap.js has been loaded?
Upvotes: 4
Views: 537
Reputation: 119827
if (typeof jQuery === 'undefined') {
throw new Error('Bootstrap\'s JavaScript requires jQuery')
}
Bootstrap only checks for jQuery globally. By the time the browser tries to load Bootstrap, jQuery may not be there yet because RequireJS loads modules asynchronously.
Now Bootstrap doesn't export itself as an AMD module. In order to ensure that RequireJS to be able to load Bootstrap as well as ensure it loads after jQuery, you use the paths and shim config. paths
maps the module name to the module file, while shim
tells RequireJS its dependencies.
paths: {
// We tell RequireJS that `bootstrap` module is this file
bootstrap: 'path/to/bootstrap.js'
},
shim: {
// We tell RequireJS that `bootstrap` will need `jquery` loaded first
bootstrap: {
deps: ['jquery'],
},
}
Then in your main.js
, load bootstrap
as one of its dependencies.
Upvotes: 3