Dynamically load a JavaScript file

后端 未结 28 3361
说谎
说谎 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:31

    An absurd one-liner, for those who think that loading a js library shouldn't take more than one line of code :P

    await new Promise((resolve, reject) => {let js = document.createElement("script"); js.src="mylibrary.js"; js.onload=resolve; js.onerror=reject; document.body.appendChild(js)});
    

    Obviously if the script you want to import is a module, you can use the import(...) function.

提交回复
热议问题