如何动态加载 JavaScript 文件?
以下是动态加载 JavaScript 文件的代码 −
示例
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Document</title> <style> body { font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif; } .result { font-size: 20px; font-weight: 500; } </style> </head> <body> <h1>Load a JavaScript file Dynamically</h1> <div style="color: green;" class="result"></div> <button class="Btn">CLICK HERE</button> <h3> Click the above button to load external JavaScript </h3> <script> let resEle = document.querySelector(".result"); document.querySelector(".Btn").addEventListener("click", () => { var jsRef = document.createElement("script"); jsRef.setAttribute("src", "sample.js"); document.getElementsByTagName("head")[0].appendChild(jsRef); }); </script> </body> </html>
script.js
resEle.innerHTML='JavaScript has been loaded';
输出
上述代码将产生以下输出 −
单击“单击此处”按钮 -
广告