← All posts

Tutorials

"Run JS once" — side-effect-free scripts on SPA pages

On single-page application (SPA) pages, JustZix re-runs a rule set's JavaScript after every address change — so the rule processes the freshly rendered view. For most scripts that is good. But for scripts with global side effects it leads to build-up. The new „Run JS once” option solves that.

The problem: a script running over and over

An SPA changes content without reloading the document. JustZix detects such navigation and runs the rule set's JS again so the rule works on the new view. But if the script adds an event listener, sets an interval (setInterval) or „wraps” a page function (such as window.fetch or dataLayer.push), every re-run adds another copy. After a few transitions you have five identical listeners, five parallel intervals and a function wrapped five times over.

The fix: the „Run JS once” checkbox

The JavaScript tab of the rule-set editor now has a „Run JS once” field (off by default — nothing changes for existing rule sets). Checked — the rule set's JS runs once per document lifetime. SPA navigation, a #hash change and the Back button no longer run it again. A full page reload always gives a fresh start.

When to check it

Turn „Run JS once” on for scripts that:

When to leave it off

Leave the option off for scripts that are meant to react to every SPA sub-view — for example ones that each time find freshly rendered elements and do something with them. If your script is idempotent (safe to run many times), you also do not need to change anything.

Good practice: idempotent code

Regardless of this option, it is worth writing scripts that are resilient to re-running. A simple pattern is a guard that aborts the script if it has already run once:

// Guard: run the logic only once per document
if (!window.__jzMyScript) {
  window.__jzMyScript = true;
  document.addEventListener('keydown', onKey);
}

The „Run JS once” option and an in-code guard are two layers of the same protection — you can use both at once.

Install JustZix and write scripts that work on SPAs without side effects piling up.

Rate this post

No ratings yet — be the first.

Try it yourself

Install JustZix and paste any snippet from this article. Two minutes from zero to a working rule across all your devices.

Get JustZix

Features · How it works · Examples · Use cases