1

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

jeroenjoosen
  • 649
  • 2
  • 10
  • 22

1 Answers1

1

contentDocument isn't supported in IE7, or more specifically, you get that error because contentDocument is not a property of _thisIframe and therefore returning undefined, which of course has no createElement() method.

Use contentWindow.document for 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).

var doc = _thisIframe.contentDocument || _thisIframe.contentWindow.document;
alex
  • 479,566
  • 201
  • 878
  • 984