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>
자세한 설명이 필요하신가요?

이 페이지의 설명만으로 궁금한 점이 모두 해결되지 않는다면 다른 AMP 사용자에게 문의하여 구체적인 활용 사례를 논의해 보세요.

Stack Overflow로 이동
설명이 부족한 기능을 발견하셨나요?

AMP 프로젝트는 여러분의 참여와 기여를 적극 환영합니다! 오픈 소스 커뮤니티를 통해 지속적으로 활동해 주셔도 좋지만 관심 있는 주제에 한 번만 기여하셔도 큰 도움이 됩니다.

GitHub에서 샘플 수정하기