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 <!doctype html> .

  • Contain a top-level
tag ( is accepted as well).

If you struggle to type the symbol, you can just copy and paste it. I prefer to just use .
  • Contain
  • and tags (these are optional in HTML).

    It is pointless if we don’t have any content in the HTML page.
  • Contain a 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
  • tag as the first child of their head tag.
  • Contain a
  • tag inside their head tag. It is also recommended to include initial-scale=1.
  • Contain a 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 rel="stylesheet" href="
    This is the regular way of using the 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 , & 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.

    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

    . 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 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

    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": ",
      },
      "triggers": {
        "trackPageview": {
          "on": "visible",
          "request": "pageview"
        }
      }
    }
    </script>
    </amp-analytics>
    

    In the above example, we have defined a request called pageview to be As discussed earlier, RANDOM is substituted by a random number, so the request may actually end up looking like

    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.

    目录
    相关文章
    |
    NoSQL 数据库 开发者
    安装部署—集群启动&amp;web ui&amp;注意事项 | 学习笔记
    快速学习 安装部署—集群启动&amp;web ui&amp;注意事项
    412 0
    安装部署—集群启动&amp;web ui&amp;注意事项 | 学习笔记
    |
    JavaScript 前端开发 Java
    Apache Oozie- 安装部署服务启动 &amp;web UI|学习笔记
    快速学习 Apache Oozie- 安装部署服务启动 &amp;web UI,本节课重点为 oozie 服务的启动与关闭,并解决页面时区显示异常的问题
    Apache Oozie- 安装部署服务启动 &amp;web UI|学习笔记
    实战项目:通讯录&amp;nbsp;UI—第十一天
     1、推出视图的两种方式:  1.通过导航控制器push到下一个界面,使用pop返回到上一个界面  2.通过模态的形式推出视图,不需要依赖于导航控制器,通过使用present到下一个界面,通过dismiss返回到上一个界面 如何选择使用哪种视图的推出方法?  秘诀:看视图之间的依赖关系  1.
    1033 0
    |
    Android开发 数据格式 XML
    Android&amp;nbsp;UI设计中的特效&amp;nbsp;界面左右…
    out_to_left.xml:         in_from_right.xml:  intent.putExtra("idnumber", IDCARD);    startActivity(intent);  //设置切换动画,从右边进入,左边退出   overridePendingTransition(R.
    939 0
    |
    11月前
    |
    开发框架 前端开发 JavaScript
    【HarmonyOS Next之旅】基于ArkTS开发(二) -> UI开发一
    本文介绍了方舟开发框架(ArkUI)及其两种开发范式:基于ArkTS的声明式开发范式和类Web开发范式。ArkUI是用于构建HarmonyOS应用界面的UI框架,提供极简UI语法和基础设施。声明式开发范式使用ArkTS语言,以组件、动画和状态管理为核心,适合复杂团队协作;类Web开发范式采用HML、CSS、JavaScript三段式开发,适用于简单界面应用,贴近Web开发者习惯。文中还概述了两者的架构和基础能力,帮助开发者选择合适的范式进行高效开发。
    354 15
    |
    11月前
    |
    编解码 前端开发 Java
    【HarmonyOS Next之旅】基于ArkTS开发(二) -> UI开发三
    本文介绍了基于声明式UI范式的图形绘制与动画效果实现方法,涵盖绘制图形、添加动画效果及常见组件说明三部分内容。在绘制图形部分,详细讲解了如何通过Circle组件为食物成分表添加圆形标签,以及使用Path组件结合SVG命令绘制自定义图形(如应用Logo)。动画效果部分则展示了如何利用animateTo实现闪屏动画,包括渐出、放大效果,并设置页面跳转;同时介绍了页面间共享元素转场动画的实现方式。最后,文章列举了声明式开发范式中的各类组件及其功能,帮助开发者快速上手构建复杂交互页面。
    374 11
    |
    7月前
    |
    存储 开发者 容器
    鸿蒙 HarmonyOS NEXT星河版APP应用开发-ArkTS面向对象及组件化UI开发使用实例
    本文介绍了ArkTS语言中的Class类、泛型、接口、模块化、自定义组件及状态管理等核心概念,并结合代码示例讲解了对象属性、构造方法、继承、静态成员、访问修饰符等内容,同时涵盖了路由管理、生命周期和Stage模型等应用开发关键知识点。
    509 1
    鸿蒙 HarmonyOS NEXT星河版APP应用开发-ArkTS面向对象及组件化UI开发使用实例
    |
    10月前
    |
    JavaScript 前端开发 UED
    【HarmonyOS Next之旅】基于ArkTS开发(二) -> UI开发四
    本文介绍了Web组件开发与性能优化的相关内容。在Web组件开发部分,涵盖创建组件、设置样式与属性、添加事件和方法以及场景示例,如动态播放视频。性能提升方面,推荐使用数据懒加载、条件渲染替代显隐控制、Column/Row替代Flex、设置List组件宽高及调整cachedCount减少滑动白块等方法,以优化应用性能与用户体验。
    331 56
    |
    10月前
    |
    编解码 UED 开发者
    【HarmonyOS Next之旅】基于ArkTS开发(二) -> UI开发之常见布局
    本文主要介绍了自适应布局与响应式布局的相关内容。自适应布局部分涵盖线性布局、层叠布局、弹性布局和网格布局,详细说明了各布局的特性及使用方法,例如线性布局中的排列、拉伸与缩放,弹性布局的方向、换行与对齐方式等。响应式布局则重点讲解了栅格系统和媒体查询,阐述如何通过栅格组件和媒体查询条件实现不同设备上的适配效果。这些技术帮助开发者灵活应对多尺寸屏幕的设计需求,提升用户体验。
    477 55
    |
    前端开发 安全 开发工具
    【11】flutter进行了聊天页面的开发-增加了即时通讯聊天的整体页面和组件-切换-朋友-陌生人-vip开通详细页面-即时通讯sdk准备-直播sdk准备-即时通讯有无UI集成的区别介绍-开发完整的社交APP-前端客户端开发+数据联调|以优雅草商业项目为例做开发-flutter开发-全流程-商业应用级实战开发-优雅草Alex
    【11】flutter进行了聊天页面的开发-增加了即时通讯聊天的整体页面和组件-切换-朋友-陌生人-vip开通详细页面-即时通讯sdk准备-直播sdk准备-即时通讯有无UI集成的区别介绍-开发完整的社交APP-前端客户端开发+数据联调|以优雅草商业项目为例做开发-flutter开发-全流程-商业应用级实战开发-优雅草Alex
    901 90
    【11】flutter进行了聊天页面的开发-增加了即时通讯聊天的整体页面和组件-切换-朋友-陌生人-vip开通详细页面-即时通讯sdk准备-直播sdk准备-即时通讯有无UI集成的区别介绍-开发完整的社交APP-前端客户端开发+数据联调|以优雅草商业项目为例做开发-flutter开发-全流程-商业应用级实战开发-优雅草Alex