Use jQuery as a dependency without loading jQuery with RequireJS?
Consider the following page:
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8/jquery.min.js"></script>
</head>
<body>
<script data-main="app" src="require.js"></script>
</body>
</html>
How can I use jQuery as a dependency for RequireJS modules if it is not loaded with RequireJS? I know jQuery provides itself as an AMD global module, so I should be able to add it as a dependency, but I'm not really sure how to.
I would like to be able to do the following:
require(['jquery'], function() {
console.log('success')
});
And if jQuery hasn't finished loading yet, it should wait for completion and continue. Can this be done?
source to share
Load jQuery first, RequireJS first. Start the main module when both are loaded.
<html>
<head>
<script src="require.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8/jquery.min.js"></script>
</head>
<body>
<script>
require(["app"], function(app){
app.runMe()
})
</script>
</body>
</html>
jQuery will NOT register as an AMD module unless it sees define.amd
floating around. The only way to get it to register itself correctly is to load RequireJS before jQuery.
source to share
One way to do this is to use the data-main attribute to load the main.js file with require.js:
<script data-main="main" src="require.js"></script>
where main.js file is flavor:
requirejs.config({
shim: { // regard the shim structure as a dependency map
'jquery': [],
'app': ['jquery'] // app code will not execute before jquery is loaded
},
waitSeconds: 20
});
require(
[
'jquery',
'app'
],
function(
$
) {
//the plugins from the dependency array have been loaded.
console.log ("jQuery and app loaded through require.js");
}
);
The example above assumes you are loading jquery.js from the same location as require.js (this is your site)
source to share