Sunday 29 March 2015

IE9: cloneNode issue

Apparently the cloneNode method gets executed in an undesirable way on IE9. You may ask why am I stuck with IE9 which in itself is a very valid question and worthy of a long discussion. However, let us stick to the original discussion for now.

My colleague and I recently did a pretty simple and innocuous implementation of PrintPreview functionality for a web application. Since we wanted to use Media Queries and other cool stuff, it made sense to implement it on JavaScript code.

  1. Clone the content of page using cloneNode function like "var body = window.document.body.cloneNode(true);"
  2. Create a new pop up window and load the cloned content in the new window.
  3. Apply media query related to Print style to ensure that print page shows up properly e.g. sidenav elements are hidden etc.

Everything worked like charm till we kept testing the implementation in Chrome, FireFox, IE11 and IE10. We did not care to test on IE9 :(. One of the test folks reported that the print preview pop up comes up as blank screen.

Interesting!! After enabling the F12 tools on IE9 (which in itself seems ancient tool now), we figured that pop up seems to execute the full page load (including network calls referred JS and CSS files). Since we had added some code in our JavaScript files that executed code on script load, it got executed in the pop up window too. Funnily, if you closed the popup and opened it again through our JS function, it increased the network calls in geometric progression fashion. Basically it was leaking resources. Consequently, after 2-3 attempts of script execution, the web page was busy in executing scripts and network calls and hence the page was blank :).

Fix:
1. Get rid of IE9. Not possible for many of us.
2. Fix the code. Remove anything that may have script inside the element before writing to the pop up window's document element. Since the pop up window was to support print preview functionality, we did not need those script features anyways. Below code snippet shows our approach for body tag - similar code had to be written for head tag too.

            var body = $(document.querySelector('body').innerHTML);
            $(body).find('script').remove();
            var popupWin = window.open('', 'Test', "width=1024,height=768,menubar=no"); 
            $(body).each(function () {
                if (this.outerHTML != undefined && this.tagName != "SCRIPT") {
                    popupWin.document.write(this.outerHTML);
                }
            });


Searching around the Internet reveals that others (Link # 1, Link # 2) did hit the same issue too and came up with their own workarounds :).

No comments:

Post a Comment