Home Web Development AMP: Building Accelerated Mobile Pages

AMP: Building Accelerated Mobile Pages

By Ruadhan O'Donoghue
books-svg-icon Book
eBook $39.99 $27.98
Print $48.99
Subscription $15.99 $10 p/m for three months
$10 p/m for first 3 months. $15.99 p/m after that. Cancel Anytime!
What do you get with a Packt Subscription?
This book & 7000+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook + Subscription?
Download this book in EPUB and PDF formats, plus a monthly download credit
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook?
Download this book in EPUB and PDF formats
Access this title in our online reader
DRM FREE - Read whenever, wherever and however you want
Online reader with customised display settings for better reading experience
What do you get with video?
Download this video in MP4 format
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with video?
Stream this video
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with Audiobook?
Download a zip folder consisting of audio files (in MP3 Format) along with supplementary PDF
What do you get with Exam Trainer?
Flashcards, Mock exams, Exam Tips, Practice Questions
Access these resources with our interactive certification platform
Mobile compatible-Practice whenever, wherever, however you want
BUY NOW $10 p/m for first 3 months. $15.99 p/m after that. Cancel Anytime!
eBook $39.99 $27.98
Print $48.99
Subscription $15.99 $10 p/m for three months
What do you get with a Packt Subscription?
This book & 7000+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook + Subscription?
Download this book in EPUB and PDF formats, plus a monthly download credit
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook?
Download this book in EPUB and PDF formats
Access this title in our online reader
DRM FREE - Read whenever, wherever and however you want
Online reader with customised display settings for better reading experience
What do you get with video?
Download this video in MP4 format
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with video?
Stream this video
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with Audiobook?
Download a zip folder consisting of audio files (in MP3 Format) along with supplementary PDF
What do you get with Exam Trainer?
Flashcards, Mock exams, Exam Tips, Practice Questions
Access these resources with our interactive certification platform
Mobile compatible-Practice whenever, wherever, however you want
  1. Free Chapter
    Ride the Lightning with AMP
About this book
Google introduced the Accelerated Mobile Pages (AMP) project to give mobile users lightning-fast response times when accessing web pages on mobile devices. AMP delivers great user experiences by providing a framework for optimizing web pages that otherwise would take much longer to load on a mobile platform. This book shows how to solve page performance issues using the mobile web technologies available today. You will learn how to build instant-loading web pages, and have them featured more prominently on Google searches. If you want your website to succeed on mobile, if you care about SEO, and if you want to stay competitive, then this book is for you! You will go on a mobile web development journey that demonstrates with concrete examples how to build lightning-fast pages that will keep your visitors on-site and happy. This journey begins by showing how to build a simple blog article-style web page using AMP. As new concepts are introduced this page is gradually refined until you will have the skills and confidence to build a variety of rich and interactive mobile web pages. These will include e-commerce product pages, interactive forms and menus, maps and commenting systems, and even Progressive Web Apps.
Publication date:
October 2017
Publisher
Packt
Pages
370
ISBN
9781786467317

 

Chapter 1. Ride the Lightning with AMP

Web performanceis immensely important. Especially on mobile. According to recent research by Google, 53 percent of your visitors will leave your site if it takes longer than three seconds to load. Let that sink in: Over half of your visitors won't get to see your message or what you have to offer if your web pages are slow. The Accelerated Mobile Pages (AMP) project exists because performance is so important. With AMP, you don't have to miss out on that 53 percent.

By constraining the HTML, CSS, and JavaScript that you can use in your web pages, along with optimized resource management and smart caching, AMP solves the performance problem on mobile, while at the same time providing a framework for delivering engaging, media-rich, and lightning-fast web pages.

The AMP project has a lightning bolt as its logo for good reason: AMP pages are lightning fast. In this book you'll learn how to ride the lightning with AMP.

In the following sections, we'll look at:

  • What AMP pages look like
  • Why the time is right for AMP
  • How AMP solves performance on mobile
  • What the basic AMP building blocks are
  • How to build your first AMP page
 

What do AMP pages look like?


AMP pages are often indistinguishable from non-AMP mobile pages. To get you excited before we dive in, let's take a look at some real-world examples to see the kinds of rich web experiences possible with AMP.

In the following images, note the Guardian's use of some common AMP components: the hamburger menu activates an animated sidebar menu, and the sidebar menu includes an expandable accordion sub-menu.

The Guardian's AMP pages include a dynamic hamburger menu with collapsible accordion sub-menu

In the next image, we see how ebay is using AMP for e-commerce: a horizontally scrolling carousel is used to promote products. Each item of the carousel contains image and text components.

In the final image, we see how Genius (genius.com) uses embedded videos within a carousel. (Incidentally, the aging rockers in this example sure knew how to turn their amps up to ride the lightning!)

Ebay and Genius.com AMP pages showing image and video carousels, and embedded videos

These examples were chosen to show that AMP isn't limited to static text and blog type pages, but that rich, interactive experiences can be built. AMP pages can include animated menus, accordions, carousels, image galleries, light boxes, embedded videos, and more. They support analytics and ad providers, and there is even an embeddable virtual reality component in development. In the following chapters, we'll see how to implement features like these and more.

 

Why now?


The importance of web performance is clear to most web developers today. Intuitively, nobody likes waiting around watching progress bars and spinners while pages load. The abundance of performance-testing services, such as webpagetest.org, Pagespeed Insights, and mobiReady.com, highlights the widespread emphasis and interest in making the web fast. But why is web performance so important on mobile?

Why performance is important on mobile

A steady stream of data has surfaced over the past few years that highlights the correlation of performance with user engagement. For example:

Clearly, performance has an impact on conversions. While the exact numbers will vary from study to study, any research you see on the subject will confirm the trend: as page load time increases, bounce rate increases, and conversion rate decreases. If your site is slow, you're going to lose out.

Mobile technology advances won't make websites fast

A commonly held view is that, as mobile technology improves, the performance problem will solve itself. On the face of it, this seems like a reasonable assumption. It's been 10 years since the original iPhone was unveiled. Back then, it had only a 2G network connection and a 412 MHz ARM CPU to deliver the web to its owner. Today, the newest iPhone model comes with a high-speed LTE network connection, and Apple's newest multi-core A11 CPU with a clock-speed of several GHz. The latest Android devices run on octa-core CPUs.

With these advances, the mobile devices in our pockets have evolved into super-computers. Surely then, mobile web performance is not a problem for these little power-houses. So why does the world need AMP now?

Unfortunately, these technology advances don't always translate into performance improvements for a number of reasons:

  • The performance gap is getting wider: While newer, faster, and better mobile devices are shipping every month, only a portion of these will ever be used by your audience. The rest of your visitors will be relying on older and slower devices. Recent research from DeviceAtlas indicated that the original iPhone 2G is still being used to browse the web. This means that on average, the performance gap between low-end and high-end devices is increasing.
  • Physical limitations of mobile technology: Device specifications aren't everything. Faster CPUs run hotter, and there is no active cooling in mobile devices. They have to dissipate heat through layers of plastic, the battery, electronics, and the screen. When they get too hot, they have to throttle down and shut off cores. So even if a user has the newest, fastest iPhone, there's no guarantee it will be running all its cores when they're needed.
  • Lie-Fi and slow cell networks: Wi-Fi networks are often oversubscribed or backed by a poor internet connection: the user's device might have full signal bars, but really the connection sucks! The same goes for cell networks. Just because a device reports that it has an LTE connection, doesn't mean it's a fast connection.

Despite technology advances, unless you take great care, your web pages can end up being slow and frustrating on mobile devices.

AMP exists because of the realization that faster devices and networks are not going to fix performance on mobile. Instead, the problem needs to be fixed from the other end: websites need to be faster. But this is only half the story.

Business cases behind AMP

Google is a business, and as such, strategic business pressures lie behind much of its activity. The AMP project is no exception.

  • Facebook Instant Articles and Apple News: Facebook and Apple launched similar technologies in the months before AMP was announced. Compared to AMP's open, web-based approach, the Apple; and Facebook services are more closed, in-app experiences focused on the presentation of static news-type content. Despite this, Google would have seen them as a competitive threat on a new front in the battle for publishers' content and readers' eyeballs. Indeed, AMP was originally viewed as a direct response to these services, although now the range of content it supports has moved beyond the capabilities of the competition.
  • Ad technology: Google makes a lot of money from ads. Ads have a notoriously bad reputation for slowing pages down, to the point that ad-blockers are now commonplace, and even come bundled with browsers. If users block ads, or leave slow sites without viewing ads, then Google doesn't make money. If Google can improve the ad experience for users, as it does in AMP, then the threat to its ad revenue stream is mitigated.

So, the AMP project was born out of a need for faster websites, the need to answer competitor threats, and the need to maintain ad revenue. Performance underpins all these reasons, and AMP is about bringing web performance to the masses.

Web performance - why are web pages slow?

Web development is difficult to get right. The web technology stack is complex, and there are many things between the web server and the user's device that can contribute to poor performance.

There are some things that you have no control over, such as the user's network quality or device grade. But there are plenty of things that affect performance that you do have control over. Some of the most significant of these factors are page size, resource loading, number of HTTP requests, and slow JavaScript execution:

  • Page size: In 2016, mobiForge (mobiforge.com) reported a sobering statistic: the average web page, at 2.3 MB, had grown as large as the original PC game, DOOM. Something is wrong when a web page needs to be the same size as a multi-level first-person shooter with an advanced 3D graphics engine. Many things can contribute to page size, including images, videos, ads, and third-party libraries (which themselves can include further third-party code).
  • Resource loading: The order in which a page's resources are loaded can significantly affect the performance of the page. A naive approach to resource loading would be to just queue up all resources and download them as the page loads. But then network bandwidth and CPU resources are wasted on downloading and rendering items that may never be seen by the user. A smarter approach is to only load items as they are needed.
  • Number of HTTP requests: Each external resource in a web page requires an HTTP request to fetch it. HTTP requests are slow, especially on mobile. HTTP requests can be reduced by inlining CSS and images where appropriate, and by including fewer external resources.
  • Slow JavaScript execution: Today, there are JavaScript libraries for just about any task you can think of. Including and using JavaScript libraries has never been easier. But this poses problems on mobile, where every library chews through precious CPU cycles, contributing to laggy and unresponsive pages.
 

What exactly is AMP?


AMP is essentially a performance optimized HTML and JavaScript framework designed to deliver content quickly. It was originally conceived as a delivery format mostly for static, news-type content. But AMP has already evolved beyond its original static content aspirations, and now rich, interactive, and engaging pages can be built. Indeed, the range of user experiences possible was underscored at the first ever AMP conference in NYC in March 2017, where a fully functional messaging app was demonstrated, as well as an e-commerce app complete with payment capabilities.

There are three main components of AMP: AMP-HTML, AMP-JS, and AMP Cache. Let's take a look at them next.

AMP-HTML

AMP-HTML is an HTML5-based markup language that's used to write AMP content. It's basically a flavor of HTML5 designed with performance in mind. It both restricts and extends the HTML tags you can use in your pages. It restricts the HTML tags you can use to ensure reliable performance, and it provides a set of custom HTML tags--AMP components--to deliver rich but constrained functionality on top of the permitted HTML tags.

Because they are HTML-based, AMP pages will run in any web browser, out of the box. Additionally, AMP-HTML is designed so that it can also be served from the AMP Cache, and when it is, further optimizations can be automatically applied.

AMP-JS

AMP-JS is a JavaScript library that powers AMP pages. It's a runtime that orchestrates the optimized loading and rendering of AMP content. To achieve lightning-fast page loads, AMP-JS follows strict web performance best practices.

AMP-HTML restricts the tags you can use so that the exact layout needed to render the page can be known in advance. The AMP-JS runtime calculates page size and converts your custom AMP-HTML tags into HTML that the browser understands. It also assumes control of the loading of resources from the browser, so that it can prioritize resources that are above-the-fold or likely to be viewed by the user.

AMP Cache

Sometimes referred to as AMP-CDN, this is the caching component of AMP. It's a free-to-use content delivery network (CDN), for caching AMP pages so that they can be rendered instantly. Anyone is free to implement and use their own CDN. AMP Cache is a key component in delivering AMP's instant-loading experience.

When AMP pages are served from the cache, they can be optimized even further. These optimizations include:

  • Resizing images to match the user's viewport (reduces page size)
  • Inlining images that are above-the-fold (reduces HTTP requests)
  • Inlining CSS (reduces HTTP requests)
  • Preloading of extended components (reduces perceived page load time)
  • Minification of HTML and CSS (reduces page size)
  • Pre-rendering of web pages in the background (reduces perceived page load time)

AMP URLs

It's worth noting that a side-effect of the AMP Cache is that AMP documents will have a separate URL for the cached version. In fact, AMP documents have three different kinds of URL. For domain example.com, these will be:

  • Original URL:https://example.com/amp_doc.html
  • AMP Cache URL:https://example-com.cdn.ampproject.org/c/s/example.com/amp_doc.html
  • AMP Viewer URL (when viewing AMP pages from Google search results):https://www.google.com/amp/example.com/amp_doc.html

Having three URLs might be a little confusing, but they're necessary for caching and pre-rendering in AMP.

 

Preparing your web server environment


Time to roll up our sleeves and get our hands dirty with some code. First we'll need to set up a web server. Since AMP is built on standard web technologies--HTML, JavaScript, and CSS--there are no special hosting requirements. To run the examples in this book, you'll need to host the example files on a web server such as Apache, NGINX or NodeJS; any web server will do. We won't go into how to set up a web server in this book, but you should have a basic understanding of working with the web server of your choice. In particular:

  • You should be able to deploy HTML files to the correct location on the server
  • In some cases AMP requires files to be served from an alternative domain or subdomain, so you should have a way to achieve this, whether it's via a virtual host or domain alias on the same server, or hosted on another server altogether
  • Unless you are working on the localhost domain, AMP requires HTTPS in some cases, so it's a good idea to have this set up too

Alternatively, if you just want to follow along without hosting the files yourself, the examples are all hosted on theampbook.com. The source code is also available on github at github.com/ruborg/amp.

 

AMP Hello World - your first AMP page


Let's take a look at the most basic AMP page possible. It consists of the AMP boilerplate code that will be used in every AMP page you write. You can find this code at /ch1/amp.html.

<!doctype html> 
<html 
> <head> <meta charset="utf-8"> <script async src="https://cdn.ampproject.org/v0.js"></script> <link rel="canonical" href="https://theampbook.com/ch1/amp.html" /> <meta name="viewport" content="width=device-width, minimum-scale=1, initial-scale=1"> <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> </head> <body>Hello World!</body> </html>

Note

Note when copying the boilerplate code: the <style amp-boilerplate>...</noscript> markup must all be on a single line. If copying from the ebook version of this book, you may run into issues with unwanted line-breaks, so it's recommended to copy the source code from the github repository for this book, or from theampbook.com.

Save this file as amp.html on your web server, and open it up in your browser (any browser will do, even a desktop browser). You should see Hello World! printed to the browser. Well done, you've created your first AMP page!

Nearly every line you see in this example is required in every AMP page you will write. Let's walk through the code and use it to highlight the minimum requirements of all AMP pages:

  • AMP pages must start with <!doctype html> followed by <html amp> or <html
    >
  • AMP pages must contain <head> and <body> tags
  • The opening <head> tag must be immediately followed by:
<meta charset="utf-8">
  • Next it must include the AMP JS library, with:
<script async src="https://cdn.ampproject.org/v0.js"></script>
  • It must contain a canonical tag pointing to its associated desktop HTML version, or pointing to itself if there is no associated page:
<link rel="canonical" href="amp.html" >
  • It must include a viewport meta tag:
<meta name="viewport" content="width=device-width,minimum-scale=1">

(initial-scale=1 is also recommended)

  • AMP pages must include the following style boilerplate within the <head>:
<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>

Note

Ironically, the AMP lightning bolt symbol

is slow to type, since you won't find it on your keyboard. It's the unicode high voltage sign character, code point U+26A1. Using copy-paste is the easiest way to get it into your documents.

Optional but recommended boilerplate

The following items are not required in AMP pages, but are recommended so that you get the most SEO benefit from your web pages:

  • Title tag: Title tags are used as a ranking signal in search engines, and are useful to users in identifying pages. You can add the title tag right after the AMP-JS <script> tag:
<title>Hello World!</title>
  • Structured metadata: Adding structured metadata allows third-party services to more efficiently index and preview your pages. For example, Facebook uses the Open Graph Protocol, while Twitter uses Twitter Cards, to extract images and specific data about your page. Additionally, Google's Top Stories Carousel supports the schema.org Article and Video categories to generate article previews such as the ones shown in the next section. To get a structured metadata preview of your page in Google search results, you need to add code similar to this to the head of your page:
<script type="application/ld+json"> 
{ 
 "@context": "http://schema.org", 
 "@type": "NewsArticle", 
 "headline": "Article headline", 
 "image": [ 
 "thumbnail1.jpg" 
 ], 
 "datePublished": "2017-03-01T08:00:00+08:00" 
 } 
</script>

Structured metadata and the AMP carousel

While structured metadata is not generally AMP specific, a significant AMP-only benefit of adding structured metadata to your page is the AMP Top Stories carousel. This is a horizontal carousel of relevant search results featured prominently on the Google search results page. Having your content featured in this carousel brings obvious SEO benefits, and so including structured meta data is highly recommended.

AMP Top Stories carousel

Validating your AMP pages

We'll be seeing more about validation in the next chapter. For now, you just need to know that your AMP pages must validate before they will be added to the AMP Cache. The easiest way to check if your page is valid is to append #development=1 to the URL of the page in the browser address bar, and open up the Developer Tools (Cmd + Opt + I on Mac, Ctrl + Shift + I on Windows), and navigate to the Console tab. You'll then get a report for your page, indicating if it's valid. The page we just created should validate as follows:

Successful AMP validation in Chrome developer console

If it's not valid, you'll get some helpful error messages for any failures. To see this in action, remove the line that begins with <link rel="canonical"...> from your code and reload the page with #development=1 at the end of the URL. This time the validator informs us that the mandatory canonical tag is missing:

AMP validation reports an error for an invalid page

You'll need to add that line back in before the page validates again. But even if it doesn't validate, it will still render in most modern web browsers, since AMP is HTML-based. You will lose out on the benefits of the AMP Cache however.

What's with the <style amp-boilerplate> code?

You might be wondering why you need to include the <style amp-boilerplate> code in every page. Even AMP's creator and tech lead, Malte Ubl, described this code as an atrocity! Unfortunately, it's a necessary evil; a hack developed by the AMP project team to avoid the infamous flash of unstyled content while the AMP page is loading.

It works like this. First, the AMP page content is hidden while it loads. Then, when the AMP-JS library has loaded, it will unhide the page after it has finished rendering it. This presents a problem, however. If the AMP-JS library was ever unavailable when a user requested the page, then the page would stay blank forever. This would be an unacceptable user experience, even if it happened only rarely.

The trick, then, is to use a CSS keyframe animation as a timeout function: if the AMP-JS library fails to make the content visible, then the CSS animation will make it visible automatically after a few seconds, and the user will still get to see some content. A simplified version of this trick, without the vendor prefixes, is shown as follows:

body { 
  animation: amp-timeout 0s 8s 1 normal forwards; 
} 
@key-frames amp-timeout { 
  0%    {opacity: 0;} 
  100%  {opacity: 1;} 
}
 

How AMP solves mobile web performance


There are many factors that can contribute to poor web performance. AMP is able to solve performance issues and deliver pages instantly because it follows web performance best practices. But AMP is not magic: anyone can build fast pages without AMP if they follow web development best practices. This is a point that the AMP team has made on several occasions: an AMP page won't be faster than a hand-tooled page, if you know what you're doing. It will be faster than the average mobile webpage, however: AMP is about bringing best practices to the masses.

In addition to the best practices that it implements, AMP imposes restrictions that developers must follow to guarantee a certain baseline performance.

Optimizations that make AMP fast

  • JavaScript: All JavaScript is loaded asynchronously and is non-blocking. No user JavaScript is allowed in the main page (although you can include JavaScript in iframes that can't block the main page render).
  • Static resource sizing: External resources such as images, videos, and ads must specify their sizes statically. This means that AMP can calculate the position of all elements and page layout before anything is downloaded.
  • CSS inlining and limitations: CSS must be inlined in the head of the AMP page and is limited to 50 KB per page. Some CSS is restricted, including the * selector, the not selector, the filter property, and the !important declaration. Only GPU-accelerated CSS animations and transitions are permitted. If the GPU can't handle an effect, then the browser must perform the required computation instead, slowing down the page render. Specifically, only transform and opacity properties can be animated.
  • Web fonts: Web fonts can only be loaded from white-listed providers.
  • Optimized resource loading: AMP takes control of resource downloading from the browser. Only items that are above-the-fold, or that are likely to be seen by the user, are fetched.
  • Efficient pre-rendering: When possible, AMP pages are pre-rendered in the background. This is where things get really interesting!

AMP pre-rendering

AMP pre-rendering deserves a special mention here. It's used to boost the loading time of pages in the AMP cache. With AMP-HTML and AMP-JS, you get fast web pages. But with pre-rendering, you get instant pages.

Pre-rendering works by using a hidden iframe to download and render AMP pages in the background, even before the user has decided to visit them. The embedding page loads a hidden iframe with the AMP page content. The browser then loads the AMP runtime and starts to render the page. Since the AMP runtime manages resource loading, nothing else is loaded by the browser at this point (although the AMP runtime might decide to download necessary above-the-fold resources).

If the user clicks a pre-rendered AMP link, all the work to render the page has already been completed, so it can be displayed instantly simply by making the iframe visible. The JavaScript component that manages the pre-rendering iframe is called the AMP Viewer.

 

Controversy and criticisms of AMP


To achieve its performance, the AMP team have made design decisions that have resulted in aspects of AMP that seem incompatible with a distributed and open web. The most contentious of these are outlined as follows:

  • The AMP cache is owned and run by Google: With the performance optimizations of AMP-HTML and AMP-JS you get fast web pages. Add pre-rendering and you get instant-loading pages. But pages are only pre-rendered when they are served from the Google controlled AMP Cache. And you only get the AMP lightning badge if your pages are pre-rendered via the cache. So this leads to an uncomfortable situation, where you only get the benefits if you agree to have your pages hosted and served from Google's servers. The URL of the cached page is not the original URL, but instead it's served from a Google domain, for example:https://www.google.com/amp/theampbook.com instead ofhttps://theampbook.com This is somewhat misleading for the user: it looks like you are on one site, but really you are still on Google's servers. Additionally for publishers, using a Google URL dilutes their brand.
  • Preferential treatment of AMP pages in search results: Google gives special treatment to AMP pages in its search results:
    • AMP pages are annotated with the AMP lightning badge and the text "AMP", to indicate that they are fast. However, fast pages that don't use AMP don't get the lightning badge. Some argue here that Google is taking advantage of its dominant position in search to push its own technology.
    • Only AMP pages can be promoted to the AMP carousel. Given its prominent position on the results page, this offers a clear SEO advantage to AMP pages over alternatives. If you are competing for positioning, then you can't afford to be outside the AMP tent. Again, it can be argued that Google is giving preferential treatment to its own technology.
  • Centrally hosted JavaScript: Every AMP page must include the AMP-JS library from a central location by including this line:<script async src="https://cdn.ampproject.org/v0.js"></script> You are not allowed to download the library and host it yourself. This means there is a central point of failure: if the library is unavailable, broken or hacked, then every AMP site will have problems.

While these are valid concerns, they have all been robustly defended by the AMP team. Take the AMP cache. According to the AMP team, the pre-render can only happen when a page is served directly from the AMP Cache, and not from the original URL. This is because Google knows that pages in the AMP Cache conform to the AMP specification, so it can guarantee that it can be efficiently pre-rendered in the background. It cannot make this guarantee about pages not served from the cache.

Likewise, the annotation of AMP pages in the search results. In the same way that it's good practice to annotate a download link with its type and size (for example download [pdf 5 MB]), isn't it acceptable to prime a user's expectation that a link will be fast and from the AMP Cache?

 

Benefits of AMP


There are many benefits to using AMP. First, AMP addresses the biggest web performance issues, which means that your pages will load more quickly. Since page speed affects user engagement, having a faster page means that you're engaging your visitors more. If you implement AMP, you're likely to see an increase in conversions. There are more success stories than can be listed here; these are just a few:

  • The Guardian reported that its AMP traffic has overtaken its non-AMP mobile traffic, and observed 8.6 percent more clicks on related content links
  • LinkedIn reported a 10 percent increase in time spent on AMP pages over non-AMP pages
  • Gizmodo reported a 3x increase in mobile page speed and a 50 percent increase in impressions
  • WompMobile reported a 105 percent increase in conversions on AMP pages and a 31 percent decrease in bounce rate

Next is the AMP Cache. If your pages are valid AMP, then they will be added to the AMP Cache automatically, and you will see further performance gains.

Then there's the AMP lightning badge of trust. Again, if your pages validate, then they will be annotated with the AMP lightning badge in Google's search results pages. With this badge, users can be confident of a speedy page load if they click your link.

Finally there is the AMP Top Stories carousel. As we saw earlier, this is a horizontally scrollable results carousel, displayed prominently, with images, early in the Google search results page. So, while Google has stated that AMP is not a ranking signal for its indexing algorithms, there is a definite SEO benefit to having your pages included in the carousel.

AMP adoption

AMP was first announced in August 2015, and launched in February 2016. At first, in Google's search results pages, AMP results were limited to the AMP carousel. But by March 2016 AMP results were being surfaced along with normal, non-AMP results. Since then AMP has seen massive adoption among publishers and search engines. The first AMP conference was held in March 2017, where the scale of its adoption became apparent, and it was reported that AMP was already the largest web components library in the world.

At the time of writing, with behemoth web services such as Pinterest and Tumblr on board, there are billions of AMP pages live on the web already. Bing is also working with Google on the project, and reportedly saw AMP adoption rates rise from 8 percent to 62 percent in one year. Baidu and Sogou, the two largest search engines in China have adopted AMP, and Yahoo Japan is also signed-up. There is an audience of billions for AMP pages.

 

So, do you need AMP?


At the first AMP conference, one of the panelists, Jeremy Keith, was asked why he implemented AMP on his site. He didn't know. After some consideration, he said it was another distribution format, like RSS, so why not?

For some, it's about reach. AMP can be thought of as another distribution format, as Keith pointed out. To maximize your reach, you should embrace as many distribution channels as you can. As noted, some of the biggest search engines in the world, including Google, Bing, and Baidu and Sogou, are indexing and surfacing AMP pages in their search results. That's an audience of billions. And if your content is featured in the AMP carousels, that's even more eyeballs for you.

For others, it's about performance. Malte Ubl reported that the Guardian's regular mobile website was faster than its AMP page. So why did the Guardian implement AMP? Despite having an already fast site, there were still performance gains to be made via the AMP Cache and its instant pre-rendering.

If your competitors are using AMP, and are featured in the AMP carousel, then they have a competitive edge on you, and it could be worth your while investigating it.

Ultimately, if your site is not performing as well as it could be and this is affecting user engagement or revenue, then you should address this. AMP is about improving performance, so it could be part of your solution. Even if you have a hand-crafted super-fast site, like the Guardian, you might still have something to gain by adopting AMP.

 

Summary


We've covered a lot of ground in this first chapter. You should now have a good idea of what AMP is and what it's capable of, the problems that it solves and how it solves them, and how it might be able to help you. In particular, you should now know:

  • What AMP is and why it exists
  • The factors that affect web performance and why it's important
  • The components that make up AMP
  • How AMP addresses web performance issues
  • How to build a basic AMP page

In the next chapter, we'll move beyond the AMP boilerplate code. We'll see how AMP custom elements and CSS are used as we start to build our own experiences. Let's go ride the lightning!

About the Author
Latest Reviews (2 reviews total)
Purchased without ptoblems.
Sviluppa AMP con chiarezza e con una molteplicità di esempi che ne facilitano l'apprendimento.
AMP: Building Accelerated Mobile Pages
Unlock this book and the full library FREE for 7 days
Start now