2

The following code works in chrome and Safari, but crashes the site in IE11:

var doc = document.implementation.createHTMLDocument("");
doc.open("replace");
doc.write(document.querySelector("html").outerHTML);
doc.close()

What I'm attempting to do is create a clone of the DOM (that doesn't load scripts/images etc) to manipulate. Any idea why this crashes IE? Is there a better way to do this? I'm using a polyfill for outerHTML (though I think it's supported in IE11) and can confirm that outerHTML works as intended.

Thank you in advance!

Sampson
  • 265,109
  • 74
  • 539
  • 565
Skaryon
  • 13
  • 4
  • Is it possible, that the code creates a kind of infinite recursion in IE? What comes to `outerHTML`, it was natively supported even in IE5 ... – Teemu Dec 19 '14 at 22:31
  • Have you considered using *cloneNode*? Why would this method not load images and scripts? – RobG Dec 19 '14 at 23:21
  • I actually don't know why it wouldn't, I just read it didn't somewhere. I think I might have found a solution using dpcumentfragments but am still experimenting. – Skaryon Dec 19 '14 at 23:31

1 Answers1

0

It doesn't seem to be the write() method which causes IE11 to crash but instead is related to close(). The best answer found on a similar issue Why won't this JavaScript (using document.open and document.write) work in Internet Explorer or Opera? found that not including the close() call stopped IE from crashing.

I had a similar issue myself:

var doc = document.implementation.createHTMLDocument('');
doc.open();
doc.write('<body><p>Hello world</p>');
doc.close(); // This is where it breaks

However I've not had any luck actually calling the method without it breaking the page. I've tried adding it to timeouts or only closing when I finished with the DOM but all seem to fail. I guess it's a case of detecting IE11 and not calling close.

if (!(window.ActiveXObject) && "ActiveXObject" in window) {
    // IE11, do nothing... may cause memory leaks...
} else {
    doc.close();
}

I've only tried IE11 but it might crash out in earlier versions of IE as well... in that case use

if ("ActiveXObject" in window) {
    // IE, do nothing... may cause memory leaks...
} else {
    doc.close();
}

Hope this helps anyone experiencing the same issue.

Community
  • 1
  • 1
R. Chappell
  • 1,184
  • 6
  • 17