Google AMP - Custom Javascript


In the previous chapters, we have studied many amp-components. We have also seen that for each component to work we need add a javascript file.

For example, for amp-iframe the script added is as follows −

<script async custom-element="amp-iframe"

We have async added to the script tag. This is the standard for amp as they load all the javascript files asynchronously. There is a custom-element attribute added which has the name of the component it is used for.

To use any amp-component if it is not a part of the core amp javascript file, the script has to be added as shown above.

We are mostly used to writing, a lot of javascript code inside pages and also include javascript file using script tag.

How can we do that in amp? So for that AMP does not allow any script code to be written or load script tag externally.

Amp has its own component to take care of the job which is suppose to be done by the additional script which is added on the page. This is basically done for performance reasons, to load the page content faster and not have javascript delay the rendering or do any changes to the DOM.

This is the specification given by AMP as per their official site for script tags −

Prohibited unless the type is application/ld+json. (Other non-executable values may be added as needed.) Exception is the mandatory script tag to load the AMP runtime and the script tags to load extended components.

A working example where we can use application/ld+json inside our amp pages is shown here. Note that we are using the script tag with type=”application/ld+json” for amp-analytics component to fire tracker.

Similarly, we can use script tag with type=”application/ld+json” on other amp-components wherever required.


<!doctype html>
<html amp>
      <meta charset = "utf-8">
      <script async src = "">
      <script async custom-element = "amp-analytics" 
         src = "">
      <link rel = "canonical" href = "ampanalytics.html">
      <meta name = "viewport" content = "width=device-width,
      minimum-scale = 1,initial-scale = 1">
      <style amp-boilerplate>
            -amp-start 8s steps(1,end) 0s 1 normal both;-moz-animation:
            -amp-start 8s steps(1,end) 0s 1 normal both;-ms-animation:
            -amp-start 8s steps(1,end) 0s 1 normal both;animation:
            -amp-start 8s steps(1,end) 0s 1 normal both
         <style amp-boilerplate>
      <h1>Google Amp - Analytics</h1>
         <script type = "application/json">
            "requests": {
               "event": "http://localhost:8080/googleamp/tracking.php?
            "triggers": {
               "trackPageview": {
                  "on": "visible",
                  "request": "event",
                  "vars": {
                     "eventId": "pageview"

When the page is hit in the browser, the tracker will be fired for pageview. It can be seen in the Google network tab as shown below.

Google network tab