I am using RequireJs to load AMD-modules on my company's main web site. We are also using requireJS to load modules hosted on separate domains. requireJS supports this using the "context"-field; ie. create a separate sandboxed environment with a separate baseUrl.
The problem at hand is when we want the two separate contexts to share a common object; eg. jquery (to avoid loading it twice) or a pubsub-implementation that trigger events in between widgets.
I've figured a way to inject modules in between contexts, using a define function together with a global requireJS
main.js - hosted on http://example.com/src/main.js
require(['jquery'], functin($){
// create sandbox/contexted instance of requireJs
var sandbox = requireJS.config({
context: "myContext",
baseUrl : 'http://otherdomain.com/src'
});
// load module (with internal dependencies) from other domain
sandbox.require(['modules/bootstrap.js'], function(bootstrap){
bootstrap.run();
});
});
bootstrap.js - eg. hosted on http://widgets.com/src/modules/bootstrap.js
define(function(){
// define jquery into sandboxed environemnt
requireJs('jquery', function($) {
define('jquery', function(){
return window.jQuery;
});
});
// obtain sandboxed instance from parent
var sandbox = requireJs.config({
context: "myContext"
});
sandbox(['jquery'], function($){
console.log($);
});
});
The problem is that if Im defining jquery (or any other module that returns a function), tje "requreJS"-way (not using globals) it will always throw an error
// define jquery into sandboxed environemnt
requireJs('jquery', function($) {
define('jquery', $);
});
Is this a bug or a feature ?