Mmh
Mmh

Reputation: 417

Detecting Javascript load event in IE9

I want to execute some part of my addon code on page load, so I'm looking for page load event in browsers.

if (window.addEventListener)
    window.addEventListener("load", func, false);
else if (window.attachEvent)
    window.attachEvent("onload", func);

function func() {
    alert("page loaded");
    //my code here
}

In Firefox I'm able to catch load event, but in IE9 I'm unable to get this. Alternately, using jQuery call:

$(document).ready(function(){
    //my code here
});

we can get this, but I need this functionality without using jQuery.

Upvotes: 0

Views: 867

Answers (2)

chris
chris

Reputation: 249

maybe you can try this

window.onload = function () {
   // do something here
};

Upvotes: 0

Konstantin Dinev
Konstantin Dinev

Reputation: 34905

This will execute in IE9:

window.onload = func;

To modify your code:

if (window.addEventListener) {
    window.addEventListener("load", func, false);
} else if (window.attachEvent) {
    window.attachEvent("onload", func);
} else {
    window['onload'] = func;
}

The more general event handler attachment would be:

function Subscribe(event, element, func) {
    if (element.addEventListener) {
        element.addEventListener(event, func, false);
    } else if (element.attachEvent) {
        element.attachEvent("on" + event, func);
    } else {
        element['on' + event] = func;
    }
}

Subscribe('load', window, func);

Upvotes: 2

Related Questions