One DOMContentLoaded event listener or multiple?

Viewed 693

Should i create only one DOMContentLoaded event listener and gather all the stuff for all my elements inside, or i can write multiple DOMContentLoaded listeners for every my element?

This:

    window.document.addEventListener('DOMContentLoaded', function() {
        var elems = document.querySelectorAll('.sidenav');
        var instances = M.Sidenav.init(elems, {edge:'right'});
    });

    window.document.addEventListener('DOMContentLoaded', function() {
        var elems = document.querySelectorAll('.collapsible');
        var instances = M.Collapsible.init(elems, {"accordion" : false});
    });

Or this:

    window.document.addEventListener('DOMContentLoaded', function() {
        var elems = document.querySelectorAll('.sidenav');
        var instances = M.Sidenav.init(elems, {edge:'right'});
        var elems2 = document.querySelectorAll('.collapsible');
        var instances2 = M.Collapsible.init(elems2, {"accordion" : false});
    });

What is more correct? Are there any caveats using multiple functions for DOMContentLoaded event? Do one overwrites the other or they both get saved and fired at their time later?

Right now i have them separately in different functions, it's more convenient for me, but i do not know if it's correct or not. Thanks.

1 Answers

By putting it in one listener function, you're reducing the fragmentation of the code, helping readability, and avoiding the situation where the next developer "fixes" missing calls in the first listener that were actually already present in the second listener.

If you have multiple source files for a single displayed page (such as with MVC shared Views loaded into a parent View), you may find that it's logical and necessary to have a listener in more than one file.

Related