I’m busy on a project and I have some extra javascript files that need to be loaded when the project is running. Now for that I have created the code below:
var script = _thisIframe.contentDocument.createElement('script');
script.type = 'text/javascript';
script.src = 'main.js?' + Math.random();
_thisIframe.contentDocument.body.appendChild(script);
This code works fine in Firefox, Safari, Chrome, Opera IE9 and IE8. But it doens’t in IE7
Here I get the following error:
SCRIPT5007: Unable to get value of the property 'createElement': object is null or undefined
The error is created when it does the createElement line.
I searched for this type of error, but I didn’t find an answer.
Thanks
contentDocumentisn’t supported in IE7, or more specifically, you get that error becausecontentDocumentis not a property of_thisIframeand therefore returningundefined, which of course has nocreateElement()method.Use
contentWindow.documentfor IE7 support.An easy way to get the correct property is to exploit the
||logical operator and its short circuiting nature, as well as JavaScript returning the last evaluated value in a condition (most times the truthy operand).