用原生js怎么动态添加一个js文件

2024-11-23 13:24:05
推荐回答(1个)
回答1:

var loadJS = function(url, callback) {
var head = document.getElementsByTagName("head")[0];
var script = document.createElement("script");
script.src = url;
var done = false;
script.onload = script.onreadystatechange = function() {
if (!done && (!this.readyState || this.readyState == "loaded" || this.readyState == "complete")) {
done = true;
callback();
script.onload = script.onreadystatechange = null;
head.removeChild(script);
}
};
head.appendChild(script);
};