docs
/
Walkthroughs

Run JavaScript on a hosted page

Where page JavaScript actually goes — the page record's style field — when inline script tags run and when they don't, and the attribute bootstrap for when you only control the HTML.

You deploy a page with a <script> block. On a normal page load it runs. Then you add a data-react placeholder, or put the code in the page's <head> and look up an element, and it quietly stops working. There is no console error.

There is a supported place for page JavaScript. It is not the HTML.

The short version

Where you put itRuns on a full page load?
Top-level style.javascript on the page recordYes — after the page's markup, so your elements exist. This is the one
<script> in the body of data.htmlYes, in place — unless the page has a data-react placeholder, which drops it
<script> in the <head> of data.htmlYes — but before the body markup, so element lookups return null
data.style.javascriptNo — nothing reads that path
Inline event-handler attributes (onclick, onload)Yes — attributes survive intact

None of these run when the visitor reaches the page by client-side navigation — a link rendered by the host's own components, such as the cart drawer or the built-in store, rental and content listings. The page is swapped in without loading a new document, so no page script runs. Plain <a href> links in your HTML and the navigate: effect load a full page, so on pages you build yourself this is the usual case.

Note the difference between style and data.style. style is a top-level field on the page record, a sibling of data — not a key inside it. Writing to data.style.javascript is silently ignored, and that mistake is what sends people looking for workarounds they do not need.

The supported path: style.javascript

The renderer collects each page's style slots — css, javascript, styleLinks, scriptLinks — and writes them into the document as real elements: the stylesheets ahead of the page, the scripts after the page's content. A script that arrives this way is a genuine <script> with a body, and it executes normally, with your markup already parsed above it.

There is no meaningful size limit in practice. Print Oxygen's /design customizer — an on-canvas text editor with font pickers, rotation, curving, flip and duplicate — is 113 KB of JavaScript in exactly this field, with data.html holding only the markup skeleton it renders into.

Writing it

JS = """
(function () {
  var form = document.getElementById("ct-form");
  if (!form) return;
  form.addEventListener("submit", function (e) {
    e.preventDefault();
    // …
  });
})();
"""

s, rec = req("GET", f"/repository/get/page/{SK}", token=t)
req("POST", f"/repository/update-partial/page/{SK}", {
    "sk": SK,
    "version": rec["version"],
    "style": {"javascript": JS},        # top level, beside "data"
}, token=t)

Read it back and confirm where it landed:

s, rec = req("GET", f"/repository/get/page/{SK}", token=t)
print("style" in rec)                   # True  — correct
print("style" in rec.get("data", {}))   # False — the wrong place

Then check it executed, on the rendered page:

// in the page's own console
window.__YOUR_FLAG     // set one at the top of your payload while developing

Keep the JavaScript in a real .js file in your source tree and have the deploy script read it into the style.javascript field. Editing a 113 KB payload as a quoted string inside a record is not a thing you want to do twice. Pair it with a style.css slot the same way.

Clearing it

"style": {} removes the slot. An empty object is treated as no script, which is the clean way to take a page back to static.

When the <script> tag in your HTML runs

On the usual path the body of data.html is written straight into the server-rendered document, so the browser parses it like a static file and runs each <script> in place on a full page load. A script sees the markup above it, not the markup below it.

Three things break that, and none of them reports an error:

  • A data-react placeholder anywhere in the body. The renderer then rebuilds the body through its virtual DOM instead of writing it out, and the <script> elements are left out of the page entirely. React presets currently render nothing anyway (see the warning below), so remove the placeholder.
  • The <head> of a full-document data.html. Its scripts run, but they are written out ahead of the body markup, so getElementById returns null at that point.
  • Client-side navigation. A page swapped in by one of the host's own links runs no page script at all (see the note at the top).

data-react presets render nothing. The React preset library has been removed and every data-react placeholder now renders as nothing — not even its own element. A page with one also loses every <script> in its body. Build the block from plain HTML, runtime attributes and custom elements instead.

style.javascript is still the place to put page code. It does not depend on the shape of data.html, survives a data-react placeholder, runs after the page's markup, and keeps a large payload out of the markup you edit.

An external <script src="…"> in the body is a real element and loads the same way. But you are then hosting and versioning a separate file, for no benefit over the style.javascript slot.

The attribute bootstrap: when you only control the HTML

Attributes survive intact, so an inline event handler runs:

<button onclick="this.parentNode.classList.toggle('open')">Menu</button>

That gives you a second route, which matters in one specific situation: your pipeline produces HTML and nothing else. A plain <script> just before </body> now does this job on a full page load, with none of the quoting rules below. The bootstrap is the older route: a static-site deploy that writes data.html and never touches the record's other fields can carry its JavaScript inside the markup, by putting the whole payload on a 1×1 image's onload:

<img alt="" aria-hidden="true" width="1" height="1"
     style="position:absolute;left:-9999px;top:0"
     src="data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7"
     onload='(function(){ /* your page script */ })()'>

The image decodes immediately from its data URI, the handler fires, and the code runs synchronously with the surrounding DOM already present. Place it just before </body>.

Prefer style.javascript. The bootstrap has real constraints — no single quotes anywhere in the payload, <, > and & must be HTML-escaped, and everything has to be one expression on one attribute. If your deploy script can write the record's style field, it should.

Rules, if you use it

No single quotes anywhere in the payload. Not in strings, not in comments, not in an apostrophe in a user-facing message:

show("We’ll email you");             // ’
show("Booked — check your inbox");   // —

HTML-escape <, > and &:

if (a < b && c > d)                   // source
if (a &lt; b &amp;&amp; c &gt; d)     // in the attribute

Generate it; never hand-write the escaping:

import html as H, re

def bootstrap(js_source):
    assert "'" not in js_source, "payload must not contain a single quote"
    payload = H.escape(re.sub(r'\s*\n\s*', ' ', js_source).strip(), quote=False)
    pixel = ("data:image/gif;base64,"
             "R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7")
    return ('<img alt="" aria-hidden="true" width="1" height="1" '
            'style="position:absolute;left:-9999px;top:0" '
            f'src="{pixel}" onload=\'{payload}\'>')

html = html.replace("</body>", bootstrap(open("page.js").read()) + "\n</body>", 1)

The assertion is not decoration. A single quote truncates the attribute at that character and the rest of your code becomes stray text in the markup — which renders as nothing and reports nothing.

One bootstrap per page. A deploy script that appends by slicing the document will re-capture a bootstrap from a previous run, and you end up with two, then three, each binding the same listeners. The symptom is duplicate records: one click, two identical submissions milliseconds apart.

IMG_RE = re.compile(r'<img alt="" aria-hidden="true"[^>]*?onload=\'[^\']*\'\s*>', re.S)

html = IMG_RE.sub('', html)                    # strip every existing bootstrap
assert '<img alt="" aria-hidden="true"' not in html
html = html.replace('</body>', bootstrap(js) + '\n</body>', 1)

Strip and regenerate — do not try to keep the right one. A dedupe pass that picks a survivor will eventually pick a corrupted one. Two payloads concatenated into a single attribute are a syntax error, the handler is never created, and the page falls silent with the attribute sitting there looking perfectly fine.

Do not split handlers from the payload

This applies to both routes, and it costs an afternoon.

<!-- the payload defines it… -->
<img … onload='window.BMswitch = function (el) { /* … */ };'>

<!-- …and this calls it -->
<button onclick="BMswitch(this)">Tab</button>

Locally this works. On the deployed page BMswitch is undefined when the click fires, even though the payload demonstrably ran. Attribute handlers on a hydrating host are not guaranteed to see globals assigned by another attribute handler.

Bind listeners with addEventListener from inside your script rather than defining globals for markup to call. If you must use an inline onclick, put the whole handler body in the attribute.

document.querySelectorAll("[data-tab]").forEach(function (el) {
  el.addEventListener("click", function () { switchTo(el); });
});

Make it idempotent either way

A page can render more than once on a hydrating host. Mark what you bind to:

(function () {
  var form = document.getElementById("ct-form");
  if (!form || form.dataset.bound) return;
  form.dataset.bound = "1";

  form.addEventListener("submit", function (e) {
    e.preventDefault();
    if (form.dataset.sending) return;      // second guard: one submit, one record
    form.dataset.sending = "1";
    // … and delete form.dataset.sending in the final .then()
  });
})();

Verifying

Check state, not the presence of a tag:

JSON.stringify({
  styleJs: !!window.__YOUR_FLAG,
  boots:   document.querySelectorAll('img[aria-hidden="true"][width="1"]').length,
  attrLen: document.querySelector('img[aria-hidden="true"]')?.getAttribute('onload')?.length,
  bound:   document.getElementById('ct-form')?.dataset.bound,
  appmint: !!window.appmint,
})
ReadingMeans
styleJs: false, and you wrote style.javascriptCheck it is top-level style, not data.style
boots: 2 or moreYour deploy script is appending, not replacing
attrLen much larger than your sourceTwo payloads concatenated — syntax error, nothing ran
bound: undefined, one boot, plausible lengthThe payload threw; look for an unescaped < or &
bound: "1"It ran

When you need more than a page script

If you need modules, a build step or a framework, you want a real frontend consuming AppEngine as an API — see Client Integration.

If you need platform functionality rather than custom logic, check whether window.appmint already covers it — cart, products, reservations, forms, drawers and toasts are all there, and data-action attributes reach them with no script at all:

<button data-action="cart.add" data-payload='{"sku":"ST-SOFA","quantity":1}'>
  Add to basket
</button>

Next: Build and deploy a whole site.