Search code examples
javascriptjqueryeventsiife

Do event listeners need to be inside IIFE?


I often see that many event listener codes are wrapped inside IIFE (function(e){}()) I felt it is unnecessary to keep the event listeners inside IIFE. for example:

Without IIFE

jQuery(window).on("load", function(){
    console.log("inside plain load");
});

With IIFE

(function(){
    jQuery(window).on("load", function(){
        console.log("inside wrapped load");
    });
}())

If we include above code together in a js file, on load event they execute only based on the order it was written.

I know that IIFE invoke itself, but what is the use of having event listeners inside it?, anyways it's gonna fire only if the event happens.

  • Is there any need to wrap event listeners inside IIFE?
  • Is event listeners inside IIFE is really a good practice?

Solution

  • For your example there is no difference.

    The main reason to use IIFE is to prevent leaking variables in the global scope.

    (function(){
        let notLeakedVariable = 'something'
        jQuery(window).on("load", function(){
            console.log("inside wrapped load");
            console.log(notLeakedVariable)
        });
    }())
    

    Without IIFE you'll leak the variable in the global scope.

    By wrapping your listener, you could even group multiple listeners and they'll share the same scope though closures.

    (function(){
        let sharedVariable = 'something'
        jQuery(window).on("load", function(){
            console.log("inside wrapped load");
            // sharedVariable is accessible 
        });
    
        jQuery(selector).on("click", function(){
            // sharedVariable is accessible 
        });
    }())