---
description: The contract for JavaScript in a template — how the sign player loads and re-applies scripts, the preseriaTemplateInit and preseriaTemplateDispose hooks, the ctx helpers that clean up timers, listeners and fetches, data updates versus template reloads, and the pattern-support table for physical and virtual rooms.
---

# Template JavaScript best practices

Onlit templates run inside the sign player's page, and the player re-applies a template many
times a day — after every gap, whenever the schedule cycles back to it, after an edit —
without reloading the browser. Code that works once in a browser tab can therefore run twice,
keep a timer alive against a DOM that no longer exists, or read a field before it is bound.
This page is the contract: how scripts are loaded, the lifecycle hooks and `ctx` helpers that
make cleanup automatic, and a support table for the common patterns. The hands-on patterns and
pitfalls — observers, inline-script scoping, re-execution errors, time travel — are on
[JavaScript patterns and pitfalls](template_js_patterns.md); what the upload rejects is on
[JavaScript rules and upload validation](javascript_rules.md).

## Physical and virtual rooms

The player handles scripts the same way for both room types; the one difference is an event:

| Room type | Template types | Script handling |
|---|---|---|
| **Physical Room** | Static, Current Item and Room Scoped templates | Scripts are loaded in order, external scripts awaited, then `preseriaTemplateInit(ctx)` runs. The `preseria-content-updated` event is **not** dispatched; react to data changes with a `MutationObserver`. |
| **Virtual Room** | Event Scoped templates | The same, and `preseria-content-updated` fires after every data refresh. |

## How the player loads your scripts

When a template is applied — a scheduled item becomes active, a gap starts, the virtual room
boots — the player:

1. Calls `window.preseriaTemplateDispose()` of the previous template, if defined, then clears
   every timer, listener and fetch registered through that template's `ctx`.
2. Replaces the page `<body>` with your template's HTML, carrying over the attributes you
   authored on `<body>` (`class`, `id`, `style`, your own `data-*`, ARIA). A black body
   background is supplied as a low-priority default, so one you set yourself wins. Onlit's own
   binding attributes (`data-field`, `data-condition`, the list containers, `data-template-id`,
   `data-attribute`, `data-html`, the time-format attributes) are ignored on `<body>` with a
   console warning — there they would rewrite or hide the whole template. Attributes on
   `<html>` are never applied: the live sign page is a blank shell whose `<html>` belongs to
   the player; only the preview, which *is* your page, shows them.
3. Applies your `<link>` and `<style>` elements. Inline rules take effect immediately; external
   stylesheets start loading but are **not** awaited, so re-measure layout that depends on one
   after it loads.
4. Re-executes every `<script>` by cloning it into the page, **one at a time, in authored
   order**, waiting for each `<script src>` to finish before the next. An external script that
   fails or takes more than 15 seconds stops holding up the rest; an inline
   `<script type="module">` is never waited for; `async` is not an opt-out.
5. Calls `window.preseriaTemplateInit(ctx)`, if defined, once every script has finished.

By then the template DOM is in place and `document.readyState` is already `"complete"`; no
`DOMContentLoaded` or `load` event fires for your template. Top-level code can use anything a
script above it defined. An inline script placed after a `<script src>` runs after the player's
first data-binding pass — it can read populated `data-field` values, but bound markup it
*creates* stays empty until the next update. Build bound markup, and read fields, inside
`preseriaTemplateInit`.

## The lifecycle API

```js
window.preseriaTemplateInit = (ctx) => {
  // initialization — use ctx.* for anything with side effects
};

window.preseriaTemplateDispose = () => {
  // optional — cleanup the ctx.* helpers do not cover
};
```

Assign both at the top level of your script, synchronously — not inside a callback, after an
`await`, or in an inline `<script type="module">`, whose assignment may land after the player
has read the hooks. Keep the assignments in one script, normally `script.js`: when several
scripts assign them, the last one in authored order wins.

Inside `preseriaTemplateInit`, use the managed APIs on `ctx` instead of the raw browser ones;
everything registered through them is cleaned up when the template is torn down:

| Method | What it does | On teardown |
|---|---|---|
| `ctx.setInterval(fn, ms)` | Starts an interval | Cleared |
| `ctx.setTimeout(fn, ms)` | Starts a timeout | Cleared |
| `ctx.addEventListener(target, type, fn, opts)` | Adds an event listener | Removed |
| `ctx.requestAnimationFrame(fn)` | Schedules one animation frame | Canceled |
| `ctx.fetch(url, opts)` | `fetch` wrapper | In-flight requests aborted |
| `ctx.onDispose(fn)` | Registers custom cleanup — a chart's `destroy()`, an observer's `disconnect()` | Called |
| `ctx.state` | A fresh object for this template instance's state | Discarded |

A raw `setInterval` or `window.addEventListener` *inside* `preseriaTemplateInit` is the
silent failure to avoid: it leaks exactly like code written before the lifecycle API existed.
Keep state in `ctx.state` or closure variables, not on `window`.

```js
window.preseriaTemplateInit = (ctx) => {
  ctx.state.pageIndex = 0;

  ctx.setInterval(() => {
    ctx.state.pageIndex++;
    renderPage(ctx.state.pageIndex);
  }, 12000);

  ctx.addEventListener(window, "preseria-content-updated", () => {
    refreshDisplay();            // update what changed, do not restart the timer
  });

  const chart = ChartLibrary.create(document.getElementById("chart"), {});
  ctx.onDispose(() => chart.destroy());
};
```

A short script with no side effects — set a piece of text once and exit — can stay a plain
IIFE; it needs no lifecycle plumbing.

## Data updates versus template reloads

Two different things happen to a running template, and they need different handling.

#### A) Data update / DOM re-render
The player fetches new JSON data and updates the DOM.
This triggers:

- `preseria-content-updated` — on virtual rooms only. The event-scoped runtime checks for
  changes every 10 seconds and re-renders its lists once a minute regardless; a list whose
  rows would be identical is left alone, so media and animations inside it are not restarted.
  Physical-room signs check every 15 seconds and re-bind fields in place without any event.

Use the event (or a `MutationObserver` on a physical room) to react *after* the DOM changed —
re-measure, refresh counters. Do not start timers or listeners there without guarding against
duplicates, and do not reset paging on every update: only when the row structure changed.

#### B) Template reload / switching templates
The player replaces the template HTML and executes scripts again.

This is what `preseriaTemplateDispose` and the `ctx` cleanups are for. If every side effect
went through `ctx`, nothing is left to do.

## Pattern support

| Pattern | Physical Room | Virtual Room | Notes |
|---|---|---|---|
| `preseriaTemplateInit(ctx)` / `preseriaTemplateDispose()` | Preferred | Preferred | Managed lifecycle with automatic cleanup (both room types) |
| `ctx.setInterval` / `ctx.setTimeout` / `ctx.addEventListener` / `ctx.fetch` | Preferred | Preferred | Auto-cleared on template teardown (both room types) |
| `preseria-content-updated` event | **Not dispatched** | Dispatched | Use a MutationObserver for data-refresh detection on Physical Room signs |
| IIFE that runs immediately | OK for stateless code | Avoid (use lifecycle API) | Fine if your script creates no timers/listeners/fetches |
| `readyState` guard | Works | Not needed | Works because `readyState` is already `"complete"` |
| `load` / `DOMContentLoaded` listener (no guard) | Will never fire | Not applicable | The browser's native events fired long before your template loaded |
| Raw `setInterval` at top level, without cleanup | Accumulates | Accumulates | Prefer `ctx.setInterval` in both room types |
| Raw `setInterval` / `addEventListener` *inside* `preseriaTemplateInit` | Leaks silently | Leaks silently | Defeats the cleanup contract — always use `ctx.*` |
| `"use strict"` at the top of an inline `<script>` | **Not supported** (silently disabled, no warning) | **Not supported** (silently disabled, no warning) | Use an external script or `<script type="module">` if you need strict mode |
| Cross-inline-`<script>` sharing of top-level `let` / `const` / `class` | **Not supported** — each inline block is scoped in isolation (`var`/`function` declarations leak onto `window` — don't rely on it) | **Not supported** — each inline block is scoped in isolation (`var`/`function` declarations leak onto `window` — don't rely on it) | Consolidate into one inline block, or move shared code into an external `script.js` |
| Inline `onclick="foo()"` calling template script code | Fragile — works only for `var`/`function` declarations, not `const`/`let` | Fragile — works only for `var`/`function` declarations, not `const`/`let` | Attach listeners via `ctx.addEventListener` inside `preseriaTemplateInit` |
| `MutationObserver` without `document.contains` guard | Fires on stale elements | Fires on stale elements | Always guard in both room types |
| Reading `data-field` values | Top-level code may see empty values; `preseriaTemplateInit(ctx)` sees populated values | Top-level code and initial `preseriaTemplateInit(ctx)` may see empty values | Physical Room templates can read bound fields in init. Event Scoped Templates should read after `preseria-content-updated` or use a MutationObserver |
| External script dependency | Awaited before init | Awaited before init | Runs in authored order — a later external script can rely on an earlier one's globals; `preseriaTemplateInit` remains the safest home for dependent init |
| Top-level `let` / `const` / `class` in an external script | **Breaks on re-application** — SyntaxError before the script runs, hooks never registered | **Breaks on re-application** — SyntaxError before the script runs, hooks never registered | Declare inside `preseriaTemplateInit`, or use `var` / `function` at top level |
| `animationstart` / `transitionstart` on initial CSS state | May fire before listener attaches | May fire before listener attaches | Start the animation from `preseriaTemplateInit`, or read `getComputedStyle` |
| Setting `window.preseriaTemplateInit` / `Dispose` after an `await` or inside a callback | Can overwrite next template's hooks | Can overwrite next template's hooks | Set the lifecycle hooks synchronously at the top of a fast-loading script |

## Example templates

Three ready-to-upload ZIPs demonstrate the API end to end; each is small enough to read in a
few minutes. They bind the system fields `room`, `title` and the time helpers, and also
reference two **demo-only** custom fields (`presenter_name`, `session_description`) that you
replace with your own JSON values or remove.

### Time-Based Layout Override

Switches between a default session card and a "Coffee Break" override layout based on the device's local time. Demonstrates:

- All logic inside `preseriaTemplateInit(ctx)` with no module-level state.
- `ctx.setInterval` drives the poll loop — the timer is cleared automatically on template switch.
- Synchronous, top-level hook assignment (no async import, no assignment inside a callback).

[Download: Time-Based Layout Override](../../assets/templates/Time-Based%20Layout%20Override.zip) — written up on [Time-based layout override](template_time_override.md).

### Live Clock and Session Countdown

Shows a wall clock that ticks every second, the scheduled item's details, and a live countdown to the session's end that turns red under five minutes and switches to an "Ended" state after the session ends. Demonstrates:

- Two parallel `ctx.setInterval` loops (clock and countdown) that are both auto-cleared on teardown.
- Reading a `data-field` value via a `MutationObserver` with a `document.contains` guard, registered through `ctx.onDispose(() => obs.disconnect())` so the observer is torn down alongside everything else.
- Parsing the system-generated `time_end` format (`"YYYY-MM-DD HH:MM:SS"`) reliably across browsers by normalizing the space to `T` before calling `new Date(...)`.

[Download: Live Clock and Session Countdown](../../assets/templates/Live%20Clock%20and%20Session%20Countdown.zip)

### Rotating Announcements Banner

Shows the scheduled item's details at the top and cycles through a list of announcements along a bottom banner, one at a time, with a short fade transition between each. Demonstrates:

- `ctx.state` for per-template-instance state (the rotation index) — no module-level variables, no `window.*` globals.
- `ctx.setInterval` for the rotation cadence and `ctx.setTimeout` for the mid-cycle fade-in, both auto-cleared on teardown.
- A CSS-driven visual transition with JS toggling a class and scheduling the swap (transition duration kept in sync between `styles.css` and `script.js`).

[Download: Rotating Announcements Banner](../../assets/templates/Rotating%20Announcements%20Banner.zip) — its `announcements` array is a hard-coded demo list; replace it with your own JSON values or load it with `ctx.fetch`.

## Related

- [JavaScript patterns and pitfalls](template_js_patterns.md)
- [JavaScript rules and upload validation](javascript_rules.md)
- [Event scoped templates](event_scoped_templates.md)
- [Embedding video](embedding_video.md) and [Embedding an HLS livestream](embedding_hls_livestream.md) — media players with the cleanup they need
- [Example templates](../example_templates.md)
