How to dynamically execute/eval JavaScript code that contains an ES6 module / requires some dependencies?

时光毁灭记忆、已成空白 提交于 2019-12-01 05:14:38
Stefan

After adding some log messages I found out that when using type="module":

  • $('body').append(script); does not execute the module code

  • body.appendChild(script); does asynchronously execute the module code but the events onload and onreadystatechange do not work, even if I use addEventListener(...) instead of script.onload =....

Following work around works for me. It modifies the user source code to include a call to a global callback:

    var sourceCode =  editor.getText(); 

    window.scriptLoadedHook = function(){
        var model = window.createModel();
        console.log('model:' + model);
        window.scriptLoadedHook = undefined;
    };

    var body = document.body;
    var script = document.createElement('script');
    script.type = 'module';
    script.innerHTML = sourceCode + "\n" + 
                       "if(window.scriptLoadedHook){window.scriptLoadedHook();}";           
    body.appendChild(script);   

I try now to find out how to use exports from the <script type="module"> tag to at least get rid of the global function window.createModel:

How to import es6 module that has been defined in <script type="module"> tag inside html?

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!