Using document.head.appendChild() to append a script tag that has an SRC attribute?

前端 未结 2 1435
情话喂你
情话喂你 2021-02-07 11:07

Any reason why the following code isn\'t working?

alert(\"1\");
document.head.appendChild(\"

        
2条回答
  •  梦毁少年i
    2021-02-07 11:23

    element.appendChild expects a node not a string. You should first create the node and set the attributes and then append it.

    element.appendChild Reference

    var sc = document.createElement("script");
    sc.setAttribute("src", "https://getfirebug.com/firebug-lite.js");
    sc.setAttribute("type", "text/javascript");
    document.head.appendChild(sc);
    

    For older browsers (IE < 9 etc.) that doesn't support document.head

    document.getElementsByTagName("head")[0].appendChild(sc);
    

提交回复
热议问题