Why won’t this JavaScript (using document.open and document.write) work in Internet Explorer or Opera?

if I take the guts of the render() function out (i.e., just put them after load() in main.js), this works fine.

Doesn’t for me in IE8. If I lose the AJAX call completely and just call render() in main.js, I get the same result. In fact even if I replace the whole of main.js with just:

document.write('hello!');

with or without opening the document, the hello never appears!

If I put any timeout (even 0) on the call to render in main.js, it works. The timeout on the parent document, on the other hand, doesn’t seem to be doing anything.

This extreme weirdness is caused by jQuery using a temporarily-inserted <script> tag to execute the code returned by in jsonp.js. If you simply call eval on the return value instead of having jQuery execute it, it works fine.

A related problem I found narrowing down the hello example is demonstrated by index.html:

<body>
<iframe name="foo"></iframe>
<script>
    var idoc= frames['foo'].document;
    idoc.open();
    idoc.write('<body><script src="https://stackoverflow.com/questions/1736886/main.js"><\/script>');
    idoc.close();
</script>

with main.js containing:

document.write('foo');

There is no foo written. (An inline script, on the other hand, was fine.)

If the idoc.close was omitted, it worked. If an additional idoc.write('bar') was added, the bar was written before foo in IE only. If I added both bar and the close call, IE crashed.

So to summarise, there are deep problems using document.write from inside a document that was itself written by document.write! Try to avoid it if at all possible. document.open can be a useful way to populate an iframe from a parent document, but you shouldn’t really be needing it inside the child document, where you can use DOM methods on yourself.

Leave a Comment