#BlackLivesMatter
Do you build things with AMP? Fill out the new AMP Developer Survey!
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"
  src="https://amp.dev/documentation/examples/components/amp-script/hello-world.js"
  class="sample">
  <button id="hello-url">Say hello!</button>
</amp-script>
在 playground 中打开此代码片段

Using an inline script

You can also include a script inline and reference it by id. Note that, on the script, you need to set type=text/plain and target=amp-script.

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

<script id="hello-world" type="text/plain" target="amp-script">
    const button = document.getElementById('hello-inline');

    button.addEventListener('click', () => {
      const h1 = document.createElement('h1');
      h1.textContent = 'Hello World!';
      document.body.appendChild(h1);
    });
  </script>
在 playground 中打开此代码片段

amp-script passes its children to your script as the virtual DOM - not the entire DOM. To your script, those children are the DOM.

Thus, document.body refers to what's inside the amp-script tag, not the actual body. document.body.appendChild(...) actually adds an element inside the amp-script element.

Using the fetch API

amp-script supports the fetch API. amp-script allows us to update the page on load if it knows that the script can't change the component's height. Here, we use fixed-height layout, and we specify the height in an HTML attribute. See the documentation for details.

The time at page load was:
<amp-script layout="fixed-height"
  height="36"
  script="time-script"
  class="sample">
  <div>The time at page load was: <span id="time"
      class="answer-text"></span></div>
</amp-script>

<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 span = document.getElementById('time');
      span.textContent = data.time;
    }

    fetchCurrentTime();
  </script>
在 playground 中打开此代码片段

Showing live data

You can also use setInterval() or setTimeout to get fresh data.

The current time is:
<amp-script layout="fixed-height"
  height="36"
  script="live-time-script"
  class="sample">
  <div>The current time is: <span id="live-time"
      class="answer-text"></span></div>
</amp-script>

<script id="live-time-script" type="text/plain" target="amp-script">
    const span = document.getElementById('live-time');

    const fetchCurrentTime = async () => {
      const response = await fetch('https://amp.dev/documentation/examples/api/time');
      const data = await response.json();
      span.textContent = data.time;
    }

    setInterval(fetchCurrentTime, 1000);
  </script>
在 playground 中打开此代码片段

Custom form validation

You can also use amp-script to implement custom form validation. This script enables the button when the input field contains only capital letters.

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

<script id="form-validation-script" type="text/plain" target="amp-script">
    const submitButton = document.getElementById('validated-input-submit');
    const validatedInput = document.getElementById('validated-input');

    function allUpper() {
      let isValid = /^[A-Z]+$/.test(validatedInput.value);

      if (isValid) {
        submitButton.removeAttribute('disabled');
      } else {
        submitButton.setAttribute('disabled', '');
      }
    }

    validatedInput.addEventListener('input', allUpper);
  </script>
在 playground 中打开此代码片段

Detecting the operating system

Your script has access to global objects like navigator. This script uses this object to try to guess your device's operating system.

Your operating system is:
<amp-script layout="fixed-height"
  height="36"
  script="user-agent-script"
  class="sample">
  <div>
    Your operating system is:
    <span id="operating-system"
      class="answer-text"></span>
  </div>
</amp-script>

<script id="user-agent-script" type="text/plain" target="amp-script">
    // Adapted with gratitude from https://stackoverflow.com/a/38241481

    function getOS() {
      const userAgent = navigator.userAgent,
            platform = navigator.platform,
            macosPlatforms = ['Macintosh', 'MacIntel', 'MacPPC', 'Mac68K'],
            windowsPlatforms = ['Win32', 'Win64', 'Windows', 'WinCE'],
            iosPlatforms = ['iPhone', 'iPad', 'iPod'];
      if (macosPlatforms.includes(platform)) {
        return 'Mac OS';
      } else if (iosPlatforms.includes(platform)) {
        return 'iOS';
      } else if (windowsPlatforms.includes(platform)) {
        return 'Windows';
      } else if (/Android/.test(userAgent)) {
        return 'Android';
      } else if (/Linux/.test(platform)) {
        return 'Linux';
      }
      return 'Unknown';
    }

    const span = document.getElementById('operating-system');
    span.textContent = getOS();
  </script>
在 playground 中打开此代码片段

Personalization

Similarly, you can use the navigator object, or other means, to personalize content for your user. The following script detects the browser's language and displays a localized greeting.

<amp-script layout="fixed-height"
  height="40"
  script="translation-script"
  class="sample">
  <h2 id="translated-greeting"></h2>
</amp-script>
<script id="translation-script" type="text/plain" target="amp-script">
    const translationMap = {
      'en': 'Hello',
      'fr': 'Bonjour',
      'es': 'Hola',
      'hi': 'हैलो',
      'zh': '你好',
      'pr': 'Olá'
    };
    const lang = navigator.language.slice(0, 2);
    const translation = translationMap[lang];
    if (!translation) {
      translation = "Couldn't recognize your language. So: Saluton";
    }

    let greeting = document.getElementById('translated-greeting');
    greeting.innerHTML = translation + '!';
  </script>
在 playground 中打开此代码片段
需要进一步说明?

如果此页面的说明未能涵盖您的所有问题,欢迎与其他 AMP 用户取得联系,讨论您的具体用例。

前往 Stack Overflow
一项无法解释的功能?

AMP 项目强烈鼓励您参与其中并作出贡献!我们希望您能成为我们开源社区的持续参与者,但我们也欢迎您对热衷问题做出单次贡献。

在 GitHub 上编辑实例