Custom JavaScript Can Be Added To AMP Pages, Said Google

Creating custom website involves custom stylesheet and custom JavaScript. For Accelerated Mobile Pages (AMP), the latter was not natively supported.

Earlier this 2019 at the AMP Conference, Google introduced the developer preview of amp-script, which is essentially an AMP component that allows users to run their own JavaScript in a separate Worker thread.

In other words, the component allows developers to add their custom JavaScript to their AMP pages, while retaining AMP's fast loading speed.

The script allows developers to cover use cases that they couldn’t with existing AMP components. It also lets them share code across their AMP and non-AMP pages.

"Now," said Google on an AMP blog post, "we are announcing the general availability of amp-script.

Below are some of the examples:

  • Todo MVC using Vue.
  • A password checker.
  • Data visualization in an article using D3.js.
  • Multi-page forms where each section needs validation before proceeding to the next section.

This is made possible using WorkerDOM, which aims to provide a full representation of the DOM inside of Web Workers. This means that scripts can be used unchanged inside of the worker environment, using library written in TypeScript.

"It hydrates server rendered DOM and then proxies mutations as an application makes changes to the page, such as reacting to user actions or running animations," said Google.

Example of multi-page form with validation between sections
Example of multi-page form with validation between sections, in an AMP page. (Credit: Google)

To benefit this script, Google said that there are some constraints:

  • Content jumping: To avoid unexpected content jumping, the script generally requires user gestures to change page content.
  • Page load: Since amp-script doesn’t change page content without user interaction, it doesn’t modify content on page load either.
  • Script size: The script used in a single amp-script must be smaller than 150kB.
  • API support: Not all APIs are supported inside a Web Worker and WorkerDOM. In addition, some DOM methods and properties are not yet implemented.

According to Google, this update was one of the most important requests from developers using AMP. This should benefit all AMP developers who are looking forward for a more flexible website.

Google also said that developers can even use a JavaScript frameworks, such as React, Preact, Angular, Vue.js, jQuery and D3.js.

Prior to this update, AMP pages have been mostly static, which limited its uses and forced developers to trade speed for features and experience. With the update, developers using AMP can finally incorporate more interactivity capabilities that JavaScript offers, but without restraining AMP benefits.

Published: 
27/08/2019