I\'m trying to have angular and jquery loaded with requirejs. The best I can do is that 50% of the time everything loads correctly, the other half I get the error No
This might be a late response but as Dustin Blake said, you can also use jQuery .ready()
instead of including another module like domReady
.
requirejs.config({
paths: {
jquery: '/path/to/jquery',
angular: 'path/to/angular'
}, shim: {
angular: {
exports: 'angular'
},
}
});
require(['jquery'], function($) {
$(document).ready(function(){
// I like it this way instead of including
// everything in the parent function so it's easier to read
require(['angular', "modules/mainApp"], function(){
angular.bootstrap(document, ['mainApp']);
})
})
});
Add Jquery as a dependency for Angular in the shim.
require.config({
paths: {
'jQuery': '//ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min',
'angular': '//ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular',
},
shim: {
'angular' : {'exports' : 'angular', deps: ['jQuery']},
'jQuery': {'exports' : 'jQuery'}
}
});
You can use domReady (UPDATED) to make sure that the DOM is fully loaded, i.e. all JS files are there, before bootstrapping your application.
requirejs.config({
paths: {
jquery: '/path/to/jquery',
angular: 'path/to/angular',
domReady: '/path/tp/domReady'
}, shim: {
angular: {
exports: 'angular'
},
}
});
define(['jquery', 'angular', 'modules/mainApp'],
function($, angular, 'mainApp') {
// tell angular to wait until the DOM is ready
// before bootstrapping the application
require(['domReady'], function() {
angular.bootstrap(document, ['mainApp']);
});
});
See the RequireJS official documentation for more information on this gotcha:
It is possible when using RequireJS to load scripts quickly enough that they complete before the DOM is ready. Any work that tries to interact with the DOM should wait for the DOM to be ready.
The trick is found on this blog post.
EDIT If you follow the blog post's advice, please use this domReady script instead of the one I previously posted: https://github.com/requirejs/domReady/blob/master/domReady.js.