简体   繁体   中英

Javascript onload not firing in IE11

I'm creating a new window using the following:

var windowX = window.open('page.html', 'newWindow', 'width=600,height=600');    

The new window is just a blank html page that contains javascript which constructs a new object, I then use that object with some more javascript that I inject after the page has loaded.

My solution works in chrome and firefox but does not appear to work in IE11. The alert does not show, nor does the following code.

windowX.onload = function() {
    //I've added the alert just to see if the onload is firing...
    windowX.alert('hello!');
    var script = document.createElement('script');
    script.type = 'text/javascript';
    script.language = 'JavaScript';
    script.src = '/scripts/newScript.js';
    windowX.document.head.appendChild(script);
};

I've attempted to use jQuery $(windowX).ready(...) & $(windowX).load(...) which still works in chrome but with no success in IE11.

I figured out the problem is that IE11 runs window.open() as a synchronous task, preventing any further javascript from running until the window has opened and loaded, so the onload event that is declared afterwards is never fired because the new window has already 'loaded'.

To get around this I check if the users browser is IE11 and fire the load event using jquery:

if (!!window.MSInputMethodContext && !!document.documentMode) {
    $(windowX).trigger('load');
}

It is ok - you cannot work with properties of unfinished object ("Unable to set property 'onload' of undefined or null reference"), but this code works in IE11 (do not need to load empty page):

var windowX = window.open('');
windowX.alert('hello!');
var script = windowX.document.createElement('script');
script.type = 'text/javascript';
script.language = 'JavaScript';
script.src = '/scripts/newScript.js';
windowX.document.head.appendChild(script);

But you are right those 2 browsers have them visible during loading (for example window.name does not exist in IE, but exist in these 2).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM