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.

相关实践学习
Serverless极速搭建Hexo博客
本场景介绍如何使用阿里云函数计算服务命令行工具快速搭建一个Hexo博客。
目录
相关文章
|
NoSQL 数据库 开发者
安装部署—集群启动&amp;web ui&amp;注意事项 | 学习笔记
快速学习 安装部署—集群启动&amp;web ui&amp;注意事项
258 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.
908 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.
846 0
|
8天前
|
搜索推荐 Android开发 开发者
探索安卓开发中的自定义视图:打造个性化UI组件
【10月更文挑战第39天】在安卓开发的世界中,自定义视图是实现独特界面设计的关键。本文将引导你理解自定义视图的概念、创建流程,以及如何通过它们增强应用的用户体验。我们将从基础出发,逐步深入,最终让你能够自信地设计和实现专属的UI组件。
|
1月前
|
开发框架 JavaScript 前端开发
鸿蒙NEXT开发声明式UI是咋回事?
【10月更文挑战第15天】鸿蒙NEXT的声明式UI基于ArkTS,提供高效简洁的开发体验。ArkTS扩展了TypeScript,支持声明式UI描述、自定义组件及状态管理。ArkUI框架则提供了丰富的组件、布局计算和动画能力。开发者仅需关注数据变化,UI将自动更新,简化了开发流程。此外,其前后端分层设计与编译时优化确保了高性能运行,利于生态发展。通过组件创建、状态管理和渲染控制等方式,开发者能快速构建高质量的鸿蒙应用。
114 3
|
25天前
|
开发框架 JavaScript 前端开发
HarmonyOS UI开发:掌握ArkUI(包括Java UI和JS UI)进行界面开发
【10月更文挑战第22天】随着科技发展,操作系统呈现多元化趋势。华为推出的HarmonyOS以其全场景、多设备特性备受关注。本文介绍HarmonyOS的UI开发框架ArkUI,探讨Java UI和JS UI两种开发方式。Java UI适合复杂界面开发,性能较高;JS UI适合快速开发简单界面,跨平台性好。掌握ArkUI可高效打造符合用户需求的界面。
82 8
|
27天前
|
JavaScript API 开发者
掌握ArkTS,打造HarmonyOS应用新视界:从“Hello World”到状态管理,揭秘鸿蒙UI开发的高效秘诀
【10月更文挑战第19天】ArkTS(ArkUI TypeScript)是华为鸿蒙系统中用于开发用户界面的声明式编程语言,结合了TypeScript和HarmonyOS的UI框架。本文介绍ArkTS的基本语法,包括组件结构、模板和脚本部分,并通过“Hello World”和计数器示例展示其使用方法。
54 1
|
6月前
|
Android开发 缓存 双11
android的基础ui组件,Android开发社招面试经验
android的基础ui组件,Android开发社招面试经验
android的基础ui组件,Android开发社招面试经验
|
1月前
|
缓存 测试技术 C#
使用Radzen Blazor组件库开发的基于ABP框架炫酷UI主题
【10月更文挑战第20天】本文介绍了使用 Radzen Blazor 组件库开发基于 ABP 框架的炫酷 UI 主题的步骤。从准备工作、引入组件库、设计主题、集成到 ABP 框架,再到优化和调试,详细讲解了每个环节的关键点和注意事项。通过这些步骤,你可以打造出高性能、高颜值的应用程序界面。
下一篇
无影云桌面