Do you build things with AMP? Fill out the new AMP Developer Survey!
AMP
  • websites

amp-script

An amp-script hello world example.

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 CSP header. Read more about this in the component documentation.

<meta name="amp-script-src" content="sha384-X8xW7VFd-a-kgeKjsR4wgFSUlffP7x8zpVmqC6lm2DPadWUnwfdCBJ2KbwQn6ADE sha384-nNFaDRiLzgQEgiC5kP28pgiJVfNLVuw-nP3VBV-e2s3fOh0grENnhllLfygAuU_M sha384-u7NPnrcs7p4vsbGLhlYHsId_iDJbcOWxmBd9bhVuPoA_gM_he4vyK6GsuvFvr2ym">

Basic usage

An amp-script element can load a JavaScript file from a URL. This is usually the best way to integrate a script as the browser needs to download the script only once.

<amp-script layout="container"
  src="https://amp.dev/documentation/examples/components/amp-script/hello-world.js"
  class="amp-script-sample">
  <button id="hello">Click!</button>
</amp-script>

This is the script in hello-world.js:

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

Inline Scripts

You can also declare scripts inline and reference them by id.

<amp-script layout="container"
  script="hello-world"
  class="amp-script-sample">
  <button id="hello2">Click!</button>
</amp-script>

This is the inlined script. Note that the type needs to be type=text/plain and the target=amp-script.

<script id="hello-world"
  type="text/plain"
  target="amp-script">
  const button = document.getElementById('hello2');
  button.addEventListener('click', () => {
    const h1 = document.createElement('h1');
    h1.textContent = 'Hello World 2!';
    document.body.appendChild(h1);
  });
</script>

document.body refers to the amp-script tag and not the actual body tag. document.body.appendChild(...) actually adds an element inside the amp-script element.

Using the fetch API

amp-script supports using the fetch API. To be able to update the page on load, we need to use the fixed-height layout instead of the container layout (and the height needs to be less than 300px).

The time is:
<amp-script layout="fixed-height"
  height="32"
  script="time-script"
  class="amp-script-sample">
  <div>The time is: <span id="time"></span></div>
</amp-script>

As amp-script code is executed inside a web worker, fetch only works with absolute URLs.

<script id="time-script"
  type="text/plain"
  target="amp-script">
  const fetchCurrentTime = async () => {
    const response = await fetch('https://amp.dev/documentation/examples/api/time');
    const data = await response.json();
    const div = document.getElementById('time');
    div.textContent = data.time;
  }
  fetchCurrentTime();
</script>

Custom form validation

You can also use amp-script to implement custom form validation. Here we set the disabled state of a button based on the input value.

<amp-script layout="container"
  script="form-validation-script"
  class="amp-script-sample"
  sandbox="allow-forms">
  <input id="validated-input"
    placeholder="Only upper case letters allowed...">
  <button id="validated-input-submit"
    disabled>Submit</button>
</amp-script>

The script adds events listeners to the input elements and sets the disabled state based on a custom regex.

<script id="form-validation-script"
  type="text/plain"
  target="amp-script">
  const submitButton = document.getElementById('validated-input-submit');
const validatedInput = document.getElementById('validated-input');
validatedInput.addEventListener('input', () => {
  const isValid = /^[A-Z]+$/.test(validatedInput.value);
  if (isValid) {
    submitButton.removeAttribute('disabled');
  } else {
    submitButton.setAttribute('disabled', '');
  }
});
</script>

Detecting Android vs iOS in AMP

amp-script is great to implement functionality not offered by AMP out-of-the-box. Here is a sample that checks if the current device is using Android or iOS.

Your user-agent is: other
<amp-script layout="container"
  script="user-agent-script"
  class="amp-script-sample">
  <div>Your user-agent is: <span id="user-agent">other</span></div>
</amp-script>

The script implementation retrieves the mobile operating system from the user agent string.

<script id="user-agent-script"
  type="text/plain"
  target="amp-script">
  function getMobileOperatingSystem() {
      const userAgent = navigator.userAgent;
      if (/android/i.test(userAgent)) {
        return "Android";
      }
      // iOS detection from: http://stackoverflow.com/a/9039885/177710
      if (/iPad|iPhone|iPod/.test(userAgent) && !window.MSStream) {
        return "iOS";
      }

      return "other";
    }

    const span = document.getElementById('user-agent');
    span.textContent = getMobileOperatingSystem();

    const pre = document.createElement('pre');
    pre.textContent = navigator.userAgent;
    span.appendChild(pre);

</script>
Besoin de plus amples explications ?

Si les explications de cette page ne répondent pas à vos questions, n'hésitez pas à contacter d'autres utilisateurs d'AMP pour discuter de votre cas d'utilisation spécifique.

Se rendre sur Stack Overflow
Une fonctionnalité n'a pas encore été expliquée ?

Le projet AMP encourage fortement votre participation et vos contributions ! Nous espérons que vous deviendrez un membre régulier de notre communauté open source, mais nous serons également ravis de recevoir des contributions ponctuelles concernant les questions qui vous intéressent particulièrement.

Modifier l'exemple sur GitHub