I want my users to be able to use JavaScript as a scripting language inside my JavaScript application. To do this, I need to dynamically execute the source code.
There seem to be two main options for dynamically executing JavaScript:
a) Use the method eval(...)
(or var func = new Function(...);
).
b) Add a <script>
node to the DOM (e.g. using $('body').append(...)
).
Both methods work fine as long as I don't use any operators import
in the dynamically executable source code. If I include instructions import
, I get an error message Unexpected identifier
.
Example user source code:
import Atom from './src/core.atom.js':
window.createTreeModel = function(){
var root = new Atom('root');
root.createChildAtom('child');
return root;
}
:
a) eval
var sourceCode = editor.getText();
window.createTreeModel = undefined;
eval(sourceCode);
var model = window.createTreeModel();
treeView.setModel(model);
b) DOM:
var sourceCode = editor.getText();
window.createTreeModel = undefined;
var script = "<script >\n"+
sourceCode + "\n" +
"</script>";
$('body').append(script);
var model = window.createTreeModel();
treeView.setModel(model);
script type="application/javascript"
b), Unexpected identifier
. type="module"
, . script DOM, .
, . , script , type='module'
. type="application/javascript"
, ... ... import
.
script :
function loadScript(sourceCode, callback){
var head = document.getElementsByTagName('head')[0];
var script = document.createElement('script');
script.type = 'application/javascript';
script.innerHTML = sourceCode;
script.onreadystatechange = callback;
script.onload = callback;
head.appendChild(script);
}
-
loadScript(sourceCode, function(){
var model = window.createModel();
console.log('model:' + model);
});
index.html <source type="module">
, . . Chrome 63.0.3239.108.
= > I. <script type="module">
DOM?
= > II. eval script, import
(, , )?
= > III. , ?
:
:
, , window.createTreeModel
, . , . , ... , - , .