Search code examples
javascriptiife

JavaScript - nubie, window.onlaod and IIFE


I have a plunker here - https://plnkr.co/edit/RZTF9uda8Cw2YQx8Gs1Y?p=preview

Its a simple event on a button

With window.onload it works but not with the IIFE.

I thought the IIFE would run once its created so is that not like once the window has loaded?

    // (function(){

    //   var btn = document.getElementById('btn1');

    //   btn.addEventListener('click', function(){
    //     alert('Hi');
    //   })

    // })();


    window.onload = function(){

      var btn = document.getElementById('btn2');

      btn.addEventListener('click', function(){
        alert('Hi');
      })

    };

Solution

  • I thought the IIFE would run once its created

    Yes, of course. (It’s kinda in the name already …)

    so is that not like once the window has loaded?

    And that is the problem.

    Your script resource is embedded in the head, meaning at the time it is executed, the HTML element you are trying to select by its id does not exist yet.

    So you either need to execute this after the element exists (window load, DOMContentReady), or embed the external script resource after the relevant HTML elements. (Placing scripts at the end of body is a general performance recommendation anyway.)