In my app there are dynamic parts that are loaded from database as string that looks like:
"define(['dependency1', 'dependency2'], function(){"+
" // function body" +
"})"
which is just a simple requireJS module, as a string. I want to lazy load the script above using async require call. So, my main requireJS script looks like:
require(["jquery"], function($){
$(document).ready(function(){
// logic to load specific script from database
var scriptString = functionToLoadTheStringAbove();
// ideally i would like to call it like this
require([scriptString], function(){
// scriptString, dependency1, dependency2 are loaded
}
});
});
How do I load those string in requireJS? I know about text plugin, but it only allow loading from files. I tried eval but it doesn't resolve dependencies correctly.
RequireJS has been a hugely influential and important tool in the JavaScript world. It's still used in many solid, well-written projects today.
Syntax. define(['module1', 'module2'], function (module1, module2) { //define the module value by returning a value return function () {}; }); You can pass a list of module names when you define a module and RequireJS can be used to retrieve these modules before executing the module.
As per RequireJS API documentation, shim lets you. Configure the dependencies, exports, and custom initialization for older, traditional "browser globals" scripts that do not use define() to declare the dependencies and set a module value. - Configuring dependencies.
1) require() In NodeJS, require() is a built-in function to include external modules that exist in separate files. require() statement basically reads a JavaScript file, executes it, and then proceeds to return the export object.
This is quite late, but I just post my solution here in case anyone needs.
So I ended up asking in requireJS forum and examining the source of text! plugin and json! plugin. The cleanest way to load module from String in RequireJS is by making your own plugin to load the String, and then use onLoad.fromText() that will eval
your String and resolve all dependencies.
Example of my plugin (let's call it db!
plugin):
define([], function(){
var db = new Database(); // string is loaded from LocalStorage
return {
load: function(name, req, onLoad, reqConfig){
db.get(name, function(err, scriptString){
if (err) onLoad(err);
else onLoad.fromText(scriptString);
});
}
}
});
You can then use the plugin like:
require(["jquery", "db!myScript"], function($, myScript){
// jQuery, myScript and its dependencies are loaded from database
});
Note:
require()
from String without eval
. This is what onLoad.fromText()
does internally. Since eval is evil, you should only use it if you know what String you're going to eval()
. If you're using it in browser extension, you might want to relax the CSP policy.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With