Listeners for load events can be asynchronous and will be awaited. Listeners for unload events need to be synchronous. Both events cannot be cancelled.

    Example:

    main.ts

    const handler = (e: Event): void => { console.log(got ${e.type} event in event handler (main)); };

    globalThis.addEventListener(“load”, handler);

    globalThis.addEventListener(“unload”, handler);

    globalThis.onunload = (e: Event): void => { console.log(got ${e.type} event in onunload function (main)); };

    console.log(“log from main script”);

    A couple notes on this example:

    • addEventListener and onload/onunload are prefixed with globalThis, but you could also use self or no prefix at all. .
    • You can use addEventListener and/or onload/onunload to define handlers for events. There is a major difference between them, let’s run the example:
    1. $ deno run main.ts
    2. log from main script
    3. got load event in event handler (imported)
    4. got load event in event handler (main)
    5. got unload event in event handler (imported)
    6. got unload event in event handler (main)

    In other words, you can use addEventListener to register multiple "load" or "unload" event handlers, but only the last loaded onload or onunload event handlers will be executed. It is preferable to use addEventListener when possible for this reason.