Dynamically load a JavaScript file

后端 未结 28 2999
说谎
说谎 2020-11-22 06:56

How can you reliably and dynamically load a JavaScript file? This will can be used to implement a module or component that when \'initialized\' the component will dynamical

28条回答
  •  清酒与你
    2020-11-22 07:32

    For those of you, who love one-liners:

    import('./myscript.js');
    

    Chances are you might get an error, like:

    Access to script at 'http://..../myscript.js' from origin 'http://127.0.0.1' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

    In which case, you can fallback to:

    fetch('myscript.js').then(r => r.text()).then(t => new Function(t)());
    

提交回复
热议问题