document.head.appendChild(element) 在 IE8 及以下报错

时间:2023-03-09 18:00:07
document.head.appendChild(element) 在 IE8 及以下报错

问题:

  在开发中会遇到动态添加 script 标签的情况。

代码如下:

 var oScript = document.createElement('script');
oScript.src = 'demo_address';
document.head.appendChild(oScript);

但是在 IE8 以下会报如下错误:

 SCRIPT5007: Unable to get value of the property 'appendChild': object is null or undefined 

查看 MDN 之后发现,在 IE9 以下不支持

document.head.appendChild(element) 在 IE8 及以下报错

解决办法:

 document.getElementsByTagName('head')[0].appendChild(oScript);