Community

Blog
×
Community Blog AMP for E-Commerce Part 1: Basic Building Blocks and UI Using AMP

AMP for E-Commerce Part 1: Basic Building Blocks and UI Using AMP

In this three-part tutorial, we will explore how to create a fully functional e-commerce mobile application using AMP.

By Sai Sarath Chandra, Alibaba Cloud Tech Share Author and Alibaba Cloud MVP

In our previous article, we looked at the basics of AMP and how we can benefit from it.

To create an appealing UI using AMP, one needs to understand the basics, components, and basic building blocks of the AMP framework. I may not be able to cover all the information of AMP in my tutorials, but I should be able equip you with enough information to help you get started. If you want to learn more, you can always explore the official AMP documentation center.

Before we get into the technical discussion, I would like to address the following question. Obviously, this is just my opinion, and you are welcome to leave a comment in the comments section below.

How Reliable Is AMP? Can I Take It to Production?

At the time of this writing, AMP is in beta. For mobile app developers, one question that remains is whether AMP is well-suited for production projects. In my opinion, yes, I feel that it is ready.

I am aware of the issues beta releases tend to have, such as frequent feature changes, bugs, and frequent updates. But for me, the benefits of AMP outweigh its disadvantages. If you are a webmaster/business owner, you'll know the importance of search engine rankings. Major search engines such as Google have already started ranking AMP-powered sites in mobile searches.

Of course, this doesn't mean that we should abandon conventional HTML pages. You should definitely support regular pages alongside AMP pages to bring more traffic to your business.

Basics of AMP

The AMP HTML Format

Use the code below to create a basic and simple AMP page for understanding the basics of AMP.

<!doctype html>
<html >
  <head>
    <meta charset="utf-8">
    <title>Sample document</title>
    <link rel="canonical" href="./regularpage.html">
    <meta name="viewport" content="width=device-width,minimum-scale=1,initial-scale=1">
    <style amp-custom>
      h1 {color: red}
    </style>
    <script type="application/ld+json">
    {
      "@context": "http://schema.org",
      "@type": "NewsArticle",
      "headline": "Article headline",
      "image": [
        "thumbnail1.jpg"
      ],
      "datePublished": "2015-02-05T08:00:00+08:00"
    }
    </script>
    <script async custom-element="amp-carousel" src="https://cdn.ampproject.org/v0/amp-carousel-0.1.js"></script>
    <style amp-boilerplate>body{-webkit-animation:-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}@-webkit-keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}@-moz-keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}@-ms-keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}@-o-keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}@keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}</style><noscript><style amp-boilerplate>body{-webkit-animation:none;-moz-animation:none;-ms-animation:none;animation:none}</style></noscript>
    <script async src="https://cdn.ampproject.org/v0.js"></script>
  </head>
  <body>
    <h1>AMP Simple Page</h1>
    <p>
      Text to fill the paragraph tag
      <amp-img src=sample.jpg width=300 height=300></amp-img>
    </p>
    <amp-ad width=300 height=250
        type="a9"
        data-aax_size="300x250"
        data-aax_pubname="test123"
        data-aax_src="302">
    </amp-ad>
  </body>
</html>

There are a lot of things that we can learn from this basic page. You may ignore this by reading them below, but believe me AMP is very strict when it comes to the rules. So please make sure you follow these conventions when performing your own development.

AMP HTML documents MUST:

  • Start with the doctype .
  • Contain a top-level <html > tag (<html amp> is accepted as well).

    If you struggle to type the symbol, you can just copy and paste it. I prefer to just use <html amp>.


  • Contain <head> and <body> tags (these are optional in HTML).

    It is pointless if we don’t have any content in the HTML page.


  • Contain a <link rel="canonical" href="$SOME_URL"> tag that points to the regular HTML version of the AMP HTML document, or to itself if no such HTML version exists.

    This is a failover plan in case the AMP version of the page is unavailable. It will redirect automatically to the regular page.


  • Contain a <meta charset="utf-8"> tag as the first child of their head tag.
  • Contain a <meta name="viewport" content="width=device-width,minimum-scale=1"> tag inside their head tag. It is also recommended to include initial-scale=1.
  • Contain a <script async src="https://cdn.ampproject.org/v0.js"> tag inside their head tag.
  • Contain the AMP boilerplate code (head > style[amp-boilerplate] and noscript > style[amp-boilerplate]) in their head tag.

    AMP boilerplate code is needed as it is responsible for the validation of the complete page. Make sure you don’t generate any space if you dynamically generate the AMP pages in your website.

This is the basic information you need to know to create an AMP page. You can visit this link to learn more about the features and restrictions of AMP:

Design and Layout

CSS

CSS is what we think of when we talk about the designing of webpages. Yes, AMP supports CSS but there is a catch; we cannot refer to the CSS style sheets except for the fonts. All of the CSS should be inline and it should be enclosed in the

tag. AMP is intended to load pages faster, so it shouldn't be dependent on the external CSS for the presentation.

This seems painful now but it is good to be this way to cut-off the extra CSS that might be present in the existing versions. I recommend you to use some online compressors to do this job for you. I typically use https://csscompressor.com. There are variety of compressors out there that you could try for your use.

Layout, Media Queries & Responsive Images

AMP supports both “media queries & element queries”, and comes with a powerful, built-in way to control the layout of individual elements. The “layout” attribute makes working with and creating fully responsive design much easier than if using CSS alone.

The layout attribute gives you easy, per-element control over how your element should render on screen. Many of these things are possible with pure CSS – but they're much harder, and require a myriad of hacks. Use the layout attribute instead.

With AMP you get one more benefit of easier creation of responsive sites with the AMP simplified html tags.

<amp-img alt="Hummingbird"
  src="images/hummingbird-wide.jpg"
  width="640"
  height="457"
  srcset="images/hummingbird-wide.jpg 640w,
            images/hummingbird-narrow.jpg 320w"
  sizes="(min-width: 650px) 50vw, 100vw"
  heights="(min-width:500px) 200px, 80%">
</amp-img>

I want to reiterate this example because images are important part of website and it express a lot.

ampimg
This is the AMP version of the tag which packs many feature we will discuss more about it below

srcset
Use the srcset attribute to control an element’s assets based on varying media expressions. In particular, use it for all amp-img tags to specify which image assets to use based on varying screen sizes.

In this simple example, srcset specifies which image to use based on the screen width. The ‘w’ descriptor tells the browser the width of each image

Heights
All AMP custom elements that allow responsive layout, also support the heights attribute. The value of this attribute is a sizes expression based on media expressions as similar to the img sizes attribute, but with two key differences:

1.It applies to the height and not width of the element.
2.Percent values are allowed, e.g. 86%. If a percent value is used, it indicates the percent of the element's width.

When the heights attribute is specified along with width and height, the layout is defaulted to responsive.

Custom Fonts

Using <link> :

<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Tangerine">

This is the regular way of using the <link> tag. There is no special syntax required, but I want to emphasize that not all the domains are whitelisted in AMP. You need to use only from specific domains or else your page will end up with errors in console. Please find the whitelisted domains below. Make sure you are getting your fonts via secured protocol (https)

Using @font-face :

You can overcome the limitation posed by tag by referring font using @font-face. Please find below snippet for the same

<style amp-custom>
  @font-face {
    font-family: "Bitstream Vera Serif Bold";
    src: url("https://somedomain.org/VeraSeBd.ttf");
  }

  body {
    font-family: "Bitstream Vera Serif Bold", serif;
  }
</style>

Here you can refer via HTTP or HTTPS based on your need.

Actions and Events

Becaues AMP doesn’t allow third-party JavaScript, AMP has given some easy and cleaner ways to use the events without much of JS. Below is the syntax of the typical event in AMP HTML Tag.

eventName:targetId[.methodName[(arg1=value, arg2=value)]]

The meaning of the syntax should be obvious. You can also listen to multiple events using the ‘;’ operator. For example

on="submit-success:lightbox1;submit-error:lightbox2"

You can also execute multiple actions for an event by using ‘,’ operator. For example

on="tap:target1.actionA,target2.actionB"

AMP defines a tap event globally that you can listen to on any HTML element (including AMP elements). It also defines the hide, show, and toggle visibility actions globally that you can trigger on any HTML element. Below is an example of using the feature.

<div id="warning-message">Warning...</div>
<button on="tap:warning-message.hide">Cool, thanks!</button>

There are several element specific events that can increase your understanding to a greater level. Please visit this link if you are interested to do so.

Multimedia & Animations

You may wonder, why doesn't AMP allow the <img>, <video> & <audio> tags? This is because AMP doesn’t rely on the traditional elements and provide their corresponding elements for these files. Here we will discuss about elements related to image, video, animation & iframes.

###amp-img
The amp-img tag is very basic for any web developer using AMP.

<amp-img src="images/sunset.jpg"
  width="264"
  height="195"
  layout="responsive">
  <noscript>
    <img src="images/sunset.jpg" width="264" height="195" />
  </noscript>
</amp-img>

layout="responsive" makes sure that the image displays responsively on different layouts.

<noscript> is used if a client intends to disable the JavaScript. If disabled, the <amp-img> element will not work. We need use this element to show the images in case the JavaScript gets disabled at client end. You will lose the features of AMP if a client disables JavaScript.

###amp-anim
This element is same as amp-img but this provides the way we can display .gif images in the site along with the fallback images if the gifs are not supported.

<amp-anim width="400"
  height="300"
  src="images/wavepool.gif">
  <amp-img placeholder
    width="400"
    height="300"
    src="images/wavepool.png">
  </amp-img>
</amp-anim>

The syntax looks obvious, but you need to keep in mind to include this dependency to make this work,

<script async custom-element="amp-anim" src="https://cdn.ampproject.org/v0/amp-anim-0.1.js"></script>

###amp-video
This element is responsible to display videos on the page.

<amp-video controls
  width="640"
  height="360"
  src="videos/kitten-playing.mp4"
  poster="images/kitten-playing.png">
  <div fallback>
    <p>This browser does not support the video element.</p>
  </div>
</amp-video>

poster is needed to show the thumbnail image of the video and the fallback text for the video is also provided in <div>. You can also apply the ‘layout=responsive’ to the element.

###amp-audio
This is needed for including an audio resource on the page. This embeds an HTML5 audio into the browser.

<amp-audio width="400"
  height="200"
  src="audio/cat-meow.mp3">
  <div fallback>
    <p>Your browser doesn’t support HTML5 audio.</p>
  </div>
  <source type="audio/mpeg"
    src="audio/cat-meow.mp3">
  <source type="audio/ogg"
    src="audio/cat-meow.ogg">
</amp-audio>

The above code snippet embeds only one audio file, but we are providing multiple formats for the browser. Keep in note that the audio files are loaded lazily as decided by the AMP.

Make sure you include this following dependency

<script async custom-element="amp-audio" src="https://cdn.ampproject.org/v0/amp-audio-0.1.js"></script>

###amp-iframe
If you would like to include any third party pages into the website, then you can use amp-iframe. This element it is similar to iframe in HTML5, but the amp-iframe element has certain restrictions.

  • Must be at least 600px or 75% of the first viewport away from the top (except for iframes that use a placeholder).
  • Can only request resources via HTTPS, and they must not be in the same origin as the container, unless they do not specify allow-same-origin.

Make sure you include the below script in the

element
<script async custom-element="amp-iframe"
  src="https://cdn.ampproject.org/v0/amp-iframe-0.1.js"></script>

Typical usage of iframe is as follows

<amp-iframe width="200" height="100"
    sandbox="allow-scripts allow-same-origin"
    layout="responsive"
    src="https://www.google.com/maps/embed/v1/place?key=AIzaSyDG9YXIhKBhqclZizcSzJ0ROiE0qgVfwzI&q=europe">
</amp-iframe>

One important thing to note here is that you cannot access the DOM of the page inside the iframe (at the time of writing).

Serving ads on AMP

Most of websites out there profit from ads. You may wonder, how well we can integrate ads in AMP. Again, AMP pages are like any other webpages with certain limitations. To serve ads, you will have to use the amp-ad element.

###amp-ad
Add the following code to the

element.

<script async custom-element="amp-ad" src="https://cdn.ampproject.org/v0/amp-ad-0.1.js"></script>

The following is the syntax for <amp-ad>

<amp-ad width="300"
    height="250"
    type="a9"
    data-aax_size="300x250"
    data-aax_pubname="test123"
    data-aax_src="302">
</amp-ad>

Note: You need to find out whether your ad provider is supported by AMP or not. Refer to this link for more information.

Analytics

AMP provides two components to meet your analytics and measurement needs: amp-pixel and amp-analytics. Both options send analytics data to a defined endpoint.

If you are looking for behavior like a simple tracking pixel, the amp-pixel component provides basic page view tracking; page view data gets sent to a defined URL. Some integrations with a vendor may call for this component, in which case they will specify the exact URL endpoint.

You can use both amp-pixel and amp-analytics in your pages: amp-pixel for simple page view tracking, and amp-analytics for everything else. You can also add multiples of each tag. If you're working with multiple analytics providers, you will need one tag per solution. Keep in mind that simpler AMP pages are better for users, so if you don’t need the extra tags, don’t use them.

###amp-analytics
To create a simple amp-analytics configuration, you must first include this custom element declaration in the <head> of the AMP document.

<script async custom-element="amp-analytics" src="https://cdn.ampproject.org/v0/amp-analytics-0.1.js"></script>

Every time a page is visible, the trigger event fires, and sends the pageview data to a defined URL along with a random ID:

<amp-analytics>
<script type="application/json">
{
  "requests": {
    "pageview": "https://foo.com/pixel?RANDOM",
  },
  "triggers": {
    "trackPageview": {
      "on": "visible",
      "request": "pageview"
    }
  }
}
</script>
</amp-analytics>

In the above example, we have defined a request called pageview to be https://foo.com/pixel?RANDOM. As discussed earlier, RANDOM is substituted by a random number, so the request may actually end up looking like https://foo.com/pixel?0.23479283687235653498734.

When the page becomes visible (as specified by the use of the trigger keyword visible), an event triggers and the pageview request is sent. The triggers attribute determines when the pageview request fires.

Wrap Up

In this tutorial, we have seen the basic building components of AMP framework. However, to make a dynamic website, we need a functional database. In our next tutorial, we will be looking at the Alibaba Cloud ApsaraDB for MongoDB and use it as a database (backend) for our AMP e-commerce website.

0 0 0
Share on

Alibaba Clouder

873 posts | 131 followers

You may also like

Comments