Permalink
Branch: master
Find file Copy path
Fetching contributors…
Cannot retrieve contributors at this time
105 lines (76 sloc) 3.83 KB
$category@ formats teaser
dynamic-content
websites
text
Allows rendering of custom UI components running on third-party JavaScript.

amp-script

amp-script

[TOC]

Allows rendering of custom UI components running on third-party JavaScript.

Availability Experimental
Required Script
<script async custom-element="amp-script" src="https://cdn.ampproject.org/v0/amp-script-0.1.js"></script>

Overview

The amp-script component allows you to render widgets and other UI using custom third-party JavaScript, e.g. a React component.

{% call callout('Important', type='caution') %} amp-script is in active development and under experimental availability. It's subject to breaking API changes and should not yet be used in production. {% endcall %}

A simple example

<!-- hello-world.html -->
<amp-script layout="container" src="https://example.com/hello-world.js">
  <button id="hello">Insert Hello World!</button>
</amp-script>
// hello-world.js
const button = document.getElementById('hello');
button.addEventListener('click', () => {
  const el = document.createElement('h1');
  el.textContent = 'Hello World!';
  // `document.body` is effectively the <amp-script> element.
  document.body.appendChild(el);
});

{% call callout('Tip', type='success') %} Enable the experiment via AMP.toggleExperiment('amp-script') in dev console. {% endcall %}

For additional code samples, see examples/amp-script/.

How does it work?

amp-script is an AMP component wrapper for worker-dom.

worker-dom runs third-party JavaScript in a web worker containing a virtual DOM. The virtual DOM listens for mutations and forwards them to the main page which reflects the changes on the real DOM.

For design details, see the "Intent to Implement" issue. For more information on worker-dom, see the @ampproject/worker-dom repository.

Interested in using <amp-script>?

We recommend developing against a local build of amp-script. This enables dev-only debugging hooks e.g. human-readable postMessage events.

See our Quick Start guide for setting up your local environment.

FAQ

  1. Which JavaScript APIs can I use?

    • Currently, most DOM elements and their properties are supported. DOM query APIs like querySelector have partial support. Browser APIs like History are not implemented yet. We'll publish an API support matrix soon.
  2. Can you support ____ API?

    • Our feature timelines are informed by your real-world use cases! Please file an issue and mention @choumx and @kristoferbaxter.