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

问题:

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

代码如下:

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

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

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

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

解决办法:

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

猜你喜欢

转载自www.cnblogs.com/weijianjun/p/10177030.html