0
0
Fork 0
mirror of https://github.com/denoland/deno.git synced 2024-10-31 09:14:20 -04:00
denoland-deno/docs/runtime/program_lifecycle.md
Bert Belder 36fde75d77
Miscellaneous documentation and spelling improvements (#5527)
* Extended/updated documentation on code editor setup and plugins.
* Moved documentation to the right file.
* Fixed spelling errors in documentation and code.
* Updated broken links.

Co-authored-by: 迷渡 <justjavac@gmail.com>
Co-authored-by: AlfieriChou <alfierichou@gmail.com>
Co-authored-by: Anil Seervi <anil13112000@gmail.com
Co-authored-by: Bert Belder <bertbelder@gmail.com>
Co-authored-by: Fernando Basso <fernandobasso.br@gmail.com>
Co-authored-by: József Sallai <jozsef@sallai.me>
Co-authored-by: S4ltyGo4t <mario.weidner@gmx.de>
Co-authored-by: Tommy May <tommymay37@gmail.com>
Co-authored-by: Turbinya <wownucleos@gmail.com>
Co-authored-by: ᴜɴвʏтᴇ <i@shangyes.net>
2020-05-17 19:24:39 +02:00

70 lines
1.9 KiB
Markdown

## 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.
Listener for `load` events can be asynchronous and will be awaited. Listener for
`unload` events need to be synchronous. Both events cannot be cancelled.
Example:
```ts
// main.ts
import "./imported.ts";
const handler = (e: Event): void => {
console.log(`got ${e.type} event in event handler (main)`);
};
window.addEventListener("load", handler);
window.addEventListener("unload", handler);
window.onload = (e: Event): void => {
console.log(`got ${e.type} event in onload function (main)`);
};
window.onunload = (e: Event): void => {
console.log(`got ${e.type} event in onunload function (main)`);
};
console.log("log from main script");
// imported.ts
const handler = (e: Event): void => {
console.log(`got ${e.type} event in event handler (imported)`);
};
window.addEventListener("load", handler);
window.addEventListener("unload", handler);
window.onload = (e: Event): void => {
console.log(`got ${e.type} event in onload function (imported)`);
};
window.onunload = (e: Event): void => {
console.log(`got ${e.type} event in onunload function (imported)`);
};
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 example:
```shell
$ deno run main.ts
log from imported script
log from main script
got load event in onload function (main)
got load event in event handler (imported)
got load event in event handler (main)
got unload event in onunload function (main)
got unload event in event handler (imported)
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`.