JS在当前页面插入标签,并执行

时间:2020-11-28 14:55:30

将<script>标签绑定到<html>上, html可换成body,header等其他存在的标签。

var htmm =document.getElementsByTagName("html")[0];
var scri = document.createElement("script");
scri.async="async"
scri.src="http://www.xxx.com/dummy.js"
scri.onload=function(){console.log("script onloaded");}
htmm.appendChild(scri);

Result:
  <script async src=​"http:​/​/www.xxx.com/​dummy.js">​</script>​
  dummy.js dummy.js:1
  script onloaded