AMP
  • websites

amp-script

Introduction

The amp-script component allows you to run custom JavaScript. Your code runs in a Web Worker, and certain restrictions apply.

Setup

First, you need to import the amp-script extension.

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

For inline scripts, you need to generate a script hash. Use the data-ampdevmode attribute to disable this requirement during development. Visit the documentation to learn more.

<meta name="amp-script-src" content="sha384-iER2Cy-P1498h1B-1f3ngpVEa9NG1xIxKqg0rNkRX0e7p5s0GYdit1MRKsELIQe8 sha384-UPY0FmlOzIjSqWqMgbuaEbqIdvpGY_FzCuTAyoLdrFJb2NYf8cPWJlugA0rUbXjL

Loading a script from a URL

To load your script from a URL, use the src attribute. This example loads and runs a script called hello.js. Valid AMP requires all URLs to be absolute and use https.

Here's the script in hello-world.js:

const button = document.getElementById('hello-url');

button.addEventListener('click', () => {
  const h1 = document.createElement('h1');
  h1.textContent = 'Hello World!';
  document.body.appendChild(h1);
});

And here's the HTML:

<amp-script layout="container"