$(window).load() in IE?

2020-02-11 11:25发布

问题:

Recently I ran into a mysterious problem that IE (6-8) is keeping throwing me an error. I don't know if this is the problem, but I think it is.

Open up the F12 developer tools in a jQuery included website, enter

$(window).load(function(){
     alert("Wont able to see me");
});

And an error will popup:

"Unable to get value of the property 'slice': object is null or undefined"

Did I do anything wrong, or anything else???

回答1:

The latest jQuery (1.7.1) with IE10 and IE9 does not produce such an error for me.

As a side note; If you wish to execute something when the dom is ready; Try this way;

$(function(){
     alert("Wont able to see me");
});

I believe this is the standard convention for attaching a function to domready event.

Reference: jQuery Documentation



回答2:

I recently found a work-around for IE not recognizing $(window).load()...

window.onload = function() {
    alert("See me, hear me, touch me!");
};

This is a little different than $(function(){}) as it executes after all elements are loaded as opposed to when the DOM is ready.

I recently implemented this in another project and it worked wonderfully.



回答3:

For anyone still running into this, IE11 (only one I tested) does not fire the the load event if the listener is inside of the jquery ready function. So pull the load function outside of the ready function and it will fire in IE11.

//this is bad
$(() => { //jquery ready
    window.onload = () => { //wont fire in IE
        cosole.log('window loaded'); 
    }
});

//this is good
$(() => { //jquery ready
    cosole.log('dom ready'); 
});

window.onload = () => { //will fire in IE
    cosole.log('window loaded'); 
}