JavaScript patterns and pitfalls¶
Template JavaScript best practices gives the contract:
scripts are re-executed on every template application, and side effects belong in
preseriaTemplateInit(ctx). This page is the field guide — the patterns that work on a
sign, the mistakes that only show up after hours of runtime, and the ones the preview hides.
Reading bound fields¶
The player binds data-field elements after the template HTML is in place, and on a
physical room it re-binds them without any event. Reading a field's text at script start
usually returns an empty string. Observe it instead, and guard against the DOM being replaced
underneath you:
window.preseriaTemplateInit = (ctx) => {
const typeEl = document.getElementById("session-type");
if (!typeEl) return;
const obs = new MutationObserver(handleUpdate);
obs.observe(typeEl, { childList: true, characterData: true, subtree: true });
ctx.onDispose(() => obs.disconnect());
function handleUpdate() {
if (!document.contains(typeEl)) { obs.disconnect(); return; }
const value = typeEl.textContent.trim().toLowerCase();
if (value === "partner session") { /* … */ }
}
handleUpdate(); // the field may already be populated
};
ResizeObserver needs the same document.contains guard. On a virtual room,
ctx.addEventListener(window, "preseria-content-updated", …) is the simpler alternative:
it fires after every data refresh.
External libraries¶
List the library before the script that uses it; scripts run in authored order and every
<script src> is awaited before preseriaTemplateInit, so there is no polling for globals:
Create the instance inside preseriaTemplateInit and destroy it in ctx.onDispose. Media
players are the usual case and need more than load order — a loop watchdog for a background
video, reconnects and destroy() for a livestream: see Embedding video
and Embedding an HLS livestream.
A third-party script that waits for DOMContentLoaded or load never starts on a sign —
those events fired long before the template was injected. The classic guard still works,
because document.readyState is already "complete", so the if branch runs at once:
if (document.readyState === "complete") setTimeout(init, 50);
else window.addEventListener("load", () => setTimeout(init, 50));
Prefer a plain call (or the lifecycle hook) in code you control; keep the guard for wrapping a library you cannot change.
Timers without the lifecycle API¶
If a script cannot use ctx.setInterval, it has to clean up after itself, because the
player replaces the whole DOM when switching templates and raw timers survive that: the old
interval keeps running, the next application of the template starts a second one, and both
poke at elements that no longer exist. Two patterns:
// Clear on re-entry: one well-known slot on window
(() => {
if (window.__myTemplateTimer) clearInterval(window.__myTemplateTimer);
window.__myTemplateTimer = setInterval(() => {
const el = document.getElementById("my-element");
if (!el) { clearInterval(window.__myTemplateTimer); window.__myTemplateTimer = null; return; }
// update el
}, 5000);
})();
// Self-terminate when the element disappears
(() => {
const id = setInterval(() => {
const el = document.getElementById("my-element");
if (!el) { clearInterval(id); return; }
// update el
}, 5000);
})();
Both collapse into a single ctx.setInterval call once you adopt the lifecycle API.
Inline scripts run in an isolated scope¶
Each inline <script> (no src, not type="module") is wrapped by the player in its own
scope. Top-level let, const and class declarations are not shared with other inline
blocks, with inline handler attributes, or as window.* properties (var and function
declarations do escape onto window — don't design around that). Three consequences:
"use strict"is silently dropped in an inline script — no error, just non-strict behavior. Use an external script or a module if you need strict mode.- Two inline scripts cannot share bindings. A
const rotate = …in one block andsetInterval(rotate, …)in the next throws rotate is not defined. Merge the blocks or move the code toscript.js. onclick="refresh()"cannot reach aconst refreshdeclared in an inline script; handler attributes resolve names onwindow. Attach listeners withctx.addEventListenerinsidepreseriaTemplateInitinstead.
Module scripts (<script type="module">) have their own strict scope and avoid all three —
but they evaluate asynchronously, so never assign the lifecycle hooks from one.
External scripts re-execute on every application¶
script.js runs from scratch each time the template is applied, in the same shared global
scope, so a top-level let, const or class throws on the second run:
The error occurs before any line runs, so window.preseriaTemplateInit = … never
executes either: the HTML renders, the JavaScript is dead. The first application of the
script is fine — there is nothing to collide with yet. It fails on every application after
that: when the sign switches back to the template (a time override, a gap, a template
change) or whenever another script in the page has already declared the same global name.
The preview masks it: preview serves your template as an ordinary page, your script
runs once normally, the preview runtime's re-run throws (visible in the preview console),
but the hook from the first run survives and the template appears to work.
// Don't: dies on re-execution
const REFRESH_MS = 5000;
window.preseriaTemplateInit = (ctx) => { /* … */ };
// Do: keep the top level to assignments; declare inside the hook
window.preseriaTemplateInit = (ctx) => {
const REFRESH_MS = 5000;
/* … */
};
If something must live at the top level of an external script, use var or a function
declaration; both tolerate re-execution. Inline blocks are not affected — the player's
wrapper makes their top-level let/const safe to re-run.
Animations that start before your listener¶
CSS is applied before scripts run, so an animation triggered by a class already in the HTML
may fire animationstart or transitionstart before you attach a listener. Either add the
triggering class from inside preseriaTemplateInit after the listener is in place, or read
getComputedStyle(el).animationName and act on the running animation directly.
The clock and time travel¶
The sign player's fakeNow and freezeTime query parameters (see
Query param overrides) simulate another date and time
for testing. They move the player's internal clock only: the active item, highlighting
and scope filtering follow the simulated time, but your own new Date() / Date.now() keep
reading the device clock. A template that derives anything from the current time in its own
JavaScript will therefore disagree with the player while time travel is active. There is no
override for it; keep that in mind when testing a time-based layout such as
Time-based layout override.
Common mistakes¶
Mistake 1: Using global intervals at top-level¶
// Don't
setInterval(nextPage, 12000);
// Do
window.preseriaTemplateInit = (ctx) => {
ctx.setInterval(nextPage, 12000);
};
Mistake 2: Re-starting pagination on every preseria-content-updated¶
If you reset paging whenever data updates, Page 1 can get “extra time” or blink.
Only reset paging when the row structure changes — items added, removed or reordered — and let data changes inside rows (a participant count, a title) update in place. Compare a list of stable keys (IDs) from the previous render to detect structural changes.
Mistake 3: Keeping state on window¶
// Don't
window.pageIndex = 0;
// Do
window.preseriaTemplateInit = (ctx) => {
ctx.state.pageIndex = 0;
};
Mistake 4: Raw browser APIs inside preseriaTemplateInit¶
setInterval, window.addEventListener or fetch called directly inside the hook are
not cleaned up — the failure is silent, an orphaned timer firing against a dead DOM. Use the
ctx.* wrappers, and ctx.onDispose for anything they do not cover.
Mistake 5: Assigning the hooks late¶
Setting window.preseriaTemplateInit inside a callback, after an await, or in an
import().then(…) can land after the next template has already assigned its own hooks
and overwrite them. The player defends against that race, but a synchronous top-level
assignment avoids it entirely.
Related¶
- Template JavaScript best practices — the contract and the
ctxAPI - JavaScript rules and upload validation
- Looping templates and Time-based layout override — small complete scripts