Program lifecycle

Deno supports browser compatible lifecycle events: load and unload. You can use these events to provide setup and cleanup code in your program.

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

  1. import "./imported.ts";
  2. const handler = (e: Event): void => {
  3. console.log(`got ${e.type} event in event handler (main)`);
  4. };
  5. window.addEventListener("load", handler);
  6. window.addEventListener("unload", handler);
  7. window.onload = (e: Event): void => {
  8. console.log(`got ${e.type} event in onload function (main)`);
  9. };
  10. window.onunload = (e: Event): void => {
  11. console.log(`got ${e.type} event in onunload function (main)`);
  12. };
  13. console.log("log from main script");

imported.ts

  1. const handler = (e: Event): void => {
  2. console.log(`got ${e.type} event in event handler (imported)`);
  3. };
  4. window.addEventListener("load", handler);
  5. window.addEventListener("unload", handler);
  6. window.onload = (e: Event): void => {
  7. console.log(`got ${e.type} event in onload function (imported)`);
  8. };
  9. window.onunload = (e: Event): void => {
  10. console.log(`got ${e.type} event in onunload function (imported)`);
  11. };
  12. console.log("log from imported script");

Note that you can use both window.addEventListener and window.onload/window.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 imported script
  3. log from main script
  4. got load event in onload function (main)
  5. got load event in event handler (imported)
  6. got load event in event handler (main)
  7. got unload event in onunload function (main)
  8. got unload event in event handler (imported)
  9. got unload event in event handler (main)

All listeners added using window.addEventListener were run, but window.onload and window.onunload defined in main.ts overrode handlers defined in imported.ts.

In other words, you can register multiple window.addEventListener "load" or "unload" events, but only the last loaded window.onload or window.onunload events will be executed.