7

I have downloaded a JS starter template. It has a default.js file like this: (Of course the js file is referenced in an html page that contains just an <a> element.)

(function () {
    "use strict";
    window.addEventListener("load", function load(event) {
        window.removeEventListener("load", load, false);
        init();
    }, false);

    function init() {
        document.getElementById("link").addEventListener("click", showAlert, false);
    }

    function showAlert() {
        alert("Welcome to Pure HTML!");
    }
}());

Now my question is why there is a window.removeEventListener in the window.addEventListener function?

1

1 Answer 1

13

It is a pattern for allowing an event handler to execute once. In the first execution of the event handler, the event handler is removed to stop it executing again.

It's interesting this is used for the window load event, as that should only fire once anyway.

1
  • addEventListener now accepts once: true as an option, which remove the handler after the first execution. Example: foo.addEventListener('click', handler, {once: true})
    – Rodolphe
    Dec 12, 2022 at 22:30

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.