Great News! Try our new tool to convert img to amp-img. Try Now!

Friday, April 12, 2019

How to use amp-script to add Custom JavaScript on AMP

With amp-script, AMP-based websites allow using JavaScript from third parties such as React Component

With amp-script, AMP-based website allow using JavaScript from third parties such as React Component

Good news for you AMP-based website developer. AMP Project as an AMP HTML developer recently announced the latest AMP component which was announced directly via Twitter @amphtml.

AMP Project announces that the <amp-script> component will soon be usable and currently can be used in experimental mode.

What is amp-script?

As we know before, an AMP document will experience a validation error if we install a third-party JavaScript inside the AMP website component.


But, with 'amp-script', custom JavaScript can be used on AMP-based website pages. For example, if you want to use the React component, you can use <amp-script> to call it.
Of course, this will be very useful for those of you who want to create an AMP website with JavaScript. JavaScript is not only one of the oldest languages for the web, but it is also almost one of the fastest growing. So now AMP will support it, developers can adopt AMP more on their web applications and websites.

How to use amp-script

Currently, amp-script is still in the experimental stage. (Read: AMP Experimental). So it can't be used in production.

To try this in Experimentl mode, open Chrome Console (CTRL+SHIFT+i or F12) and add below code on Console.

AMP.toggleExperiment('experiment')


But on the official page of amp.dev, it is explained simply by using amp-script, an example like the one below.

<!--hello-world.html -->
<amp-script layout="container" src="https://example.com/hello-world.js">
<button id="hello">Insert Hello World!</button>
</amp-script>

And below is JavaScript on hello-world.js

// 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);
});

Read full on the amp.dev.

Read more articles: