Event listener adding method supported by all major web browsers

I need to write a piece of code that will attach a listener to the selected event, and this will work in any popular browser in any version. After some searching, I came out with the following function:

function addListener(event, thefunction)
{
    if(window.addEventListener)
    {
        //All browsers, except IE before version 9.
        window.addEventListener(event, thefunction, false);
    } 
    else if(window.attachEvent)
    {
        //IE before version 9.
        window.attachEvent(event, thefunction);
    }
}

Pretty simple and seems self-evident.

Perhaps there was some problem with the event DOMContentLoaded, since no version of IE (AFAIK) recognizes it, and developers are required to use it instead onreadystatechange. The solution to this problem also seems pretty simple as long as Internet Explorer 9. You should only write an additional line in else if(window.attachEvent):

event = (event == 'DOMContentLoaded') ? 'onreadystatechange' : "on" + event;

Internet Explorer, , .

Internet Explorer 9 ( )? Microsoft , attachEvent addEventListener. onreadystatechange DOMContentLoaded.

window.addEventListener, DOMContentLoaded onreadystatechange , DOMContentLoaded.

, - ( ) window.addEventListener, , script IE 9 , DOMContentLoaded onreadystatechange ( on, IE), ?

, , , , , DOMContentLoaded onreadystatechange IE 8 ( FF/Chrome).

jQuery .on() ( )? - , - DOMContentLoaded, , script, , ?

+5
2

DOMContentLoaded IE9 W3C addEventListener, IE9:

document.addEventListener('DOMContentLoaded', function() {
    console.log('DOM ready');
}, false);

IE 9 .

jQuery 1.x IE6 + . jQuery - DOM, IE6-8 DOM ready handler:

$(function() {
    //DOM has loaded, put your code here
});

.on() , .

+3

IE9 DOMContentLoaded. . .

* , addEventListener , DOMContentLoaded.

(* - Opera 8 Safari 3.0, , ).

jQuery, DOMContentLoaded, , DOM-ready, DOM, , document.body. DOM-ready:

$(function() {

on().

, jQuery .

+5

All Articles