document.head.appendChild(element) ie ie7 and ie8
Asked Answered
H

2

18

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?

Hexapla answered 14/6, 2013 at 2:32 Comment(1)
The head property of the document object was introduced in HTML5, so any browser that isn't fully HTML5 compliant may not support it. The HTML5 specification is a "living" document, so there is no way to specify when it was introduced (i.e. in what version), which makes it difficult to determine which browsers may not support it other than by trial and error.Raskind
L
37

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);
Ladon answered 14/6, 2013 at 2:36 Comment(1)
MDN is not a definitive reference for Microsoft applications, better to reference MSDN (which says the same thing, but is a more authoritative source).Raskind
F
15

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

Try this instead:

var head = document.getElementsByTagName("head")[0];
head.appendChild(requireTag);
Floorer answered 14/6, 2013 at 2:32 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.