var script = document.createElement('script');
script.src = "//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js";
script.type='text/javascript';
var done = false;
script.onload = script.onreadystatechange = function() {
if (!done && (!this.readyState || this.readyState == "loaded" || this.readyState == "complete")) {
done = true;
promptForUserEntries();
}
};
document.getElementsByTagName("head")[0].appendChild(script);
这会在第一个Head中注入一个脚本。我有三个其他脚本,我以相同的方式插入主题,现在我正在寻找如何一次在一个标签中插入多个脚本。
谢谢
答案 0 :(得分:1)
var scripts = ["/path/to/script.js", "/path/to/script2.js"];
for (index = 0; index < scripts.length; ++index) {
var script = document.createElement('script');
script.src = scripts[index];
script.type='text/javascript';
var done = false;
script.onload = script.onreadystatechange = function() {
if (!done && (!this.readyState || this.readyState == "loaded" || this.readyState == "complete")) {
done = true;
//promptForUserEntries();
}
};
document.getElementsByTagName("head")[0].appendChild(script);
}
这将循环遍历您的脚本数组,并附加它们
答案 1 :(得分:0)
这里是根据Ole的回答修改的解决方案。它同时允许带有src标签和脚本块的脚本-例如,对于在获得Cookie同意后加载Google Analytics(分析)代码很有用。
/**
* Append a block of script code to the head
* Code can contain scripts with src attribute
* and script blocks
*/
function appendScriptBlocks (code) {
let tempEl = document.createElement('div')
tempEl.innerHTML = code
let scripts = tempEl.getElementsByTagName('script')
for (let index = 0; index < scripts.length; ++index) {
var script = document.createElement('script');
script.type= 'text/javascript';
if(scripts[index].src) {
script.src = scripts[index].src;
}
else {
script.innerHTML = scripts[index].innerHTML
eval(scripts[index].innerHTML)
}
document.getElementsByTagName('head')[0].appendChild(script);
}
}