简体   繁体   中英

document.head.appendChild(element) ie ie7 and ie8

i am having an issue appending a script to the head in ie7/8

this is the code i am using

var requireTag = document.createElement('script');
requireTag.setAttribute('type',         'text/javascript');
requireTag.setAttribute('src',          link+ 'require.js');
requireTag.setAttribute('data-main',    link+ 'data');

document.head.appendChild(requireTag);

this is the error i get

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

I found this createElement error in IE8 and tried updating my code to have

var appendChild = document.head.appendChild(requireTag);

but still get the same error. Can anyone help?

According to https://developer.mozilla.org/en-US/docs/Web/API/document.head and http://msdn.microsoft.com/en-us/library/gg593004%28v=vs.85%29.aspx , document.head isn't available to IE<9. Just use

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

I believe document.head isn't supported in those browsers.

Try this instead:

var head = document.getElementsByTagName("head")[0];
head.appendChild(requireTag);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM