Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/460.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 使用document.head.appendChild()附加具有SRC属性的脚本标记?_Javascript - Fatal编程技术网

Javascript 使用document.head.appendChild()附加具有SRC属性的脚本标记?

Javascript 使用document.head.appendChild()附加具有SRC属性的脚本标记?,javascript,Javascript,以下代码不起作用的原因是什么 alert("1"); document.head.appendChild("<script type=\"text/javascript\" src=\"https://getfirebug.com/firebug-lite.js\"></script>"); alert("2"); 警报(“1”); 文件。头。子项(“”); 警报(“2”); (我知道它正在断开,因为1已发出警报,但2未发出警报。) 完成同样事情的正确方法是什么?也就

以下代码不起作用的原因是什么

alert("1");
document.head.appendChild("<script type=\"text/javascript\" src=\"https://getfirebug.com/firebug-lite.js\"></script>");
alert("2");
警报(“1”);
文件。头。子项(“”);
警报(“2”);
(我知道它正在断开,因为1已发出警报,但2未发出警报。)

完成同样事情的正确方法是什么?也就是说,将一个脚本标记附加到文档头,其中标记使用SRC属性获取一个.js文件。我不希望它以内联方式编写javascript


谢谢

元素。appendChild
需要节点而不是字符串。您应该首先创建节点并设置属性,然后附加它

对于不支持


这将在不创建新对象的情况下满足原始海报的要求

document.head.innerHTML += "<script type=\"text/javascript\" src=\"https://getfirebug.com/firebug-lite.js\"></script>";
document.head.innerHTML+=”;
脚本将附加到现有头部部分的末尾,该部分可能不是您想要的

信不信由你,这将使您的脚本位于标题部分的开头,而不会删除现有的标题部分:

document.head.innerHTML = "<script type=\"text/javascript\" src=\"https://getfirebug.com/firebug-lite.js\"></script>" + document.head.innerHTML;
document.head.innerHTML=”“+document.head.innerHTML;

您在开发人员控制台中看到了哪些错误?可能是重复的
document.head.innerHTML += "<script type=\"text/javascript\" src=\"https://getfirebug.com/firebug-lite.js\"></script>";
document.head.innerHTML = "<script type=\"text/javascript\" src=\"https://getfirebug.com/firebug-lite.js\"></script>" + document.head.innerHTML;