动态创建script标签

/**
  * 动态加载script:
  * url和innerHTML均为可选参数
  */
function loadScript(url, innerHTML) {
  var scripts = document.getElementsByTagName("script");
  var lastScript = scripts[scripts.length - 1];
  var script = document.createElement("script");
  script.async = true;
  if (url != undefined) {
    script.src = url;
  }
  if (innerHTML != undefined) {
    script.innerHTML = innerHTML;
  }
  lastScript.parentNode.insertBefore(script, lastScript);
}


loadScript("https://example.com/myscript.js");

var scriptContent = 'console.log("Hello, World!");';
loadScript(undefined, scriptContent);
copy success
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23