Reputation: 1821
I tried to import a module dynamically. The module to choose should depend on some conditions (for this example I used random mode).
requirejs.config({
paths: {
'test': 'test/'
}
});
define([], function() {
function Chart(id, data) {
if (!(this instanceof Chart)) {
throw new TypeError("Chart constructor cannot be called as a function.");
}
console.log("chart");
};
return (Chart);
});
define([], function() {
function Chart2(id, data) {
if (!(this instanceof Chart2)) {
throw new TypeError("Chart constructor cannot be called as a function.");
}
console.log("chart2");
};
return (Chart2);
});
This option works, but it's necessary to import both scripts. So, it's not optimal.
require(['test/chart','test/chart2'], function () {
var id = Math.floor(Math.random() * 2);
var modules = ['chart','chart2'];
var chart = require('test/' + modules[id]);
console.log(chart);
});
Output: Chart() or Chart2()
This option is asynchronous. Print the object before loading the module.
require([], function () {
var chart = null;
var id = Math.floor(Math.random() * 2);
var modules = ['chart','chart2'];
require(['test/' + modules[id]], function (Chart) {
chart = new Chart();
});
console.log(chart);
});
Output: null
this option produces load error.
require([], function () {
var id = Math.floor(Math.random() * 2);
var modules = ['chart','chart2'];
var chart = require('test/' + modules[id]);
console.log(chart);
});
Output: error
Please help me with the proper way to load a module dynamically.
Upvotes: 1
Views: 1378
Reputation: 7823
RequireJS
is async, except if the module was previous loaded, so, this is your only option
var id = Math.floor(Math.random() * 2);
var modules = ['chart','chart2'];
require(['test/' + modules[id]], function (Chart) {
var chart = new Chart();
console.log(chart); // add your logic here
});
If you want to have the logic outside of the require
callback, use a function
var id = Math.floor(Math.random() * 2);
var modules = ['chart','chart2'];
require(['test/' + modules[id]], function (Chart) {
var chart = new Chart();
myLogic(chart); // call function and pass "chart"
});
function myLogic(chart) {
console.log(chart); // add your logic here
}
Please, note I've added a function named myLogic
that receive chart
as an argument.
Hope it helps.
Upvotes: 0