Ways to add javascript files dynamically in a page

后端 未结 9 1644
盖世英雄少女心
盖世英雄少女心 2020-11-28 09:16

I have seen Scriptaculous.js file to include its required javascript files dynamically. Is there any better approach to include javascript dynamically.

For example,

9条回答
  •  醉酒成梦
    2020-11-28 09:54

    Create a script tag, set the URL, add it to the document:

    let script = document.createElement("script");
    script.src = "https://example.com/your_script.js"; 
    document.body.appendChild(script);
    

    That's it. There are too many overly complicated answers on this page for such a simple task.

    If you're using modern JavaScript, you can use dynamic importing with a syntax like await import(...). That's out of the scope of this answer, but you can read more about that here.

提交回复
热议问题