Skip to content

Scripts and native HTML

The HTML works first. A script only adds to it.

A script for a component

  • A script is plain JavaScript in js/<name>.js. It exports default function (element). The element has data-lb="<name>". The script loads only when the element comes near the screen.
  • For clicks on HTML that arrives later, use one listener on a parent that stays.
  • Clean up with an AbortController. Pass its signal to every listener, and abort it when the part goes away.
  • Never write an inline script whose text differs per page. Each variant would need its own hash in the security policy.

Native HTML first

  • A panel that opens from a button is a popover. Use <button commandfor="x" command="toggle-popover"> and <div id="x" popover>. The browser opens and closes it, returns the focus, and keeps aria-expanded right.
  • A modal is <dialog closedby="any">. <button commandfor="x" command="close"> closes it.
  • Call $v->useNative() in the template. Then polyfills only load in a browser without popovers or invoker commands.
  • Content that a script hides, such as tabs, gets hidden="until-found". Then find in page still reaches it.

Events

Some modules do something that a site may want to hook into. Such a module dispatches lb:<module>-<what> on its element. That is a CustomEvent that bubbles, with detail. Listen for those events, instead of reaching into the markup of a module.

Forms and embeds

  • Forms come with every step and field in the HTML. Their conditions are in data-logic. The script of the engine shows one step at a time, and hides what does not apply. A field that may be hidden gets data-required, not required.
  • Date fields use the own controls of the browser. The script only fills them in.
  • Maps and videos in a text wait for the consent category of their kind. Until then, a box of the same size shows a button. The frame comes once the visitor agrees.

When to use a custom element

No theme uses one today. The loader and event delegation cover what they are often used for. A custom element alone is not faster.

Consider one only when it gives less work at runtime, less script, or easier upkeep. An example is a part with a lifecycle of its own, such as timers or observers, inside HTML that is often replaced. Then follow these rules:

  • Use no Shadow DOM, because the CSS of the theme must reach it.
  • The HTML of the server inside it works without a script.
  • Abort its listeners in disconnectedCallback.

Also called: front-end JavaScript, progressive enhancement, web components.

Last changed