34,79 €
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.
Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:
Seitenzahl: 347
Veröffentlichungsjahr: 2017
BIRMINGHAM - MUMBAI
Copyright © 2017 Packt Publishing
All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.
Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, nor Packt Publishing, and its dealers and distributors will be held liable for any damages caused or alleged to be caused directly or indirectly by this book.
Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.
First published: September 2017
Production reference: 1270917
ISBN 978-1-78646-731-7
www.packtpub.com
Author
Ruadhan O'Donoghue
Copy Editor
Safis Editing
Reviewer
Jeff Deskins
Project Coordinator
Ritika Manoj
Commissioning Editor
Amarabha Banerjee
Proofreader
Safis Editing
Acquisition Editor
Siddharth Mandal
Indexer
Mariammal Chettiyar
ContentDevelopmentEditor
Arun Nadar
Graphics
Jason Monteiro
Technical Editor
Shweta Jadhav
Production Coordinator
Shantanu Zagade
Ruadhan O'Donoghue is a web and mobile developer based in Ireland. He has worked in web development since 1999, and developed his first mobile web application back when the mobile web was built on WAP and WML and was browsed on tiny monochrome phone screens.Since then, he has gained experience in many different roles, including as Head of Engineering at dotMobi (Afilias), where he created mobile solutions for companies worldwide. He has been an editor with and contributor to the mobile technology site mobiForge.com for over 10 years, and publishes articles on mobile web development regularly.He currently runs his own web development agency, Western Technological.You can contact Ruadhan by any of the following means:Email:[email protected]:@rodono(https://twitter.com/rodono)Personal site:https://ruadhan.com
I'd like to thank my partner, Eadaoin, who, with her big heart, has kept me fed over the past seven months, and with her big brain, has added valuable contributions to this book.Also to Ronan Cremin, James Pearce, and Jo Rabin, all former work colleagues and mentors to me back in the dotMobi days when every year was going to be the year of the mobile web.To the AMP Project and its contributors, without whom there would only be empty space where this book is now.To Arun, Siddharth, and the team at Packt, who gently kept the pressure on to bring this book to completion.To the Superfriends, who provided the comic relief.Finally, to my mum, who has always been supportive of whatever I've chosen to do in life.Thank you!
Jeff Deskins has been building commercial websites since 1995. He loves to turn ideas into working solutions. Lately, he has been working with Docker and Kubernetes and is continuously learning best practices for high-performance sites.
Prior to his internet development career, he worked for 13 years as a television news photographer, including shooting live satellite shots for CBS News and CNN during breaking news events. Jeff continues to provide internet solutions for television stations through his TVstats.com website.
For support files and downloads related to your book, please visit www.PacktPub.com. Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at www.PacktPub.comand as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at [email protected] for more details.
At www.PacktPub.com, you can also read a collection of free technical articles, sign up for a range of free newsletters and receive exclusive discounts and offers on Packt books and eBooks.
https://www.packtpub.com/mapt
Get the most in-demand software skills with Mapt. Mapt gives you full access to all Packt books and video courses, as well as industry-leading tools to help you plan your personal development and advance your career.
Fully searchable across every book published by Packt
Copy and paste, print, and bookmark content
On demand and accessible via a web browser
Thanks for purchasing this Packt book. At Packt, quality is at the heart of our editorial process. To help us improve, please leave us an honest review on this book's Amazon page at http://www.amazon.in/dp/1786467313.
If you'd like to join our team of regular reviewers, you can email us [email protected]. We award our regular reviewers with free eBooks and videos in exchange for their valuable feedback. Help us be relentless in improving our products!
Preface
What this book covers
What you need for this book
Who this book is for
Conventions
Reader feedback
Customer support
Downloading the example code
Downloading the color images of this book
Errata
Piracy
Questions
Ride the Lightning with AMP
What do AMP pages look like?
Why now?
Why performance is important on mobile
Mobile technology advances won't make websites fast
Business cases behind AMP
Web performance - why are web pages slow?
What exactly is AMP?
AMP-HTML
AMP-JS
AMP Cache
AMP URLs
Preparing your web server environment
AMP Hello World - your first AMP page
Optional but recommended boilerplate
Structured metadata and the AMP carousel
Validating your AMP pages
What's with the <style amp-boilerplate> code?
How AMP solves mobile web performance
Optimizations that make AMP fast
AMP pre-rendering
Controversy and criticisms of AMP
Benefits of AMP
AMP adoption
So, do you need AMP?
Summary
Building Your First AMP Page
Going from HTML to AMP-HTML
Including the AMP-JS library
Validating your AMP pages
Developer tools console
Online validator
Command line validation
Fixing AMP validation errors
AMP boilerplate validation errors
Using JavaScript in AMP pages
Using CSS in AMP pages
Your first AMP component - <amp-img>
Layout in AMP
HTML tags that aren't allowed in AMP
Forbidden HTML tags
HTML tags with AMP-HTML replacements
HTML tags that are allowed, but with restrictions
AMP components
Measuring AMP page performance
Measuring mobile web performance
What is "good" web performance?
Waterfall charts
WebPagetest.org
PageSpeed Insights
Remote debugging with developer tools
Summary
Making an Impression - Layout and Page Design in AMP
Laying out elements in AMP pages
The AMP-HTML layout system
The layout attribute
Using responsive layout
Canonical AMP pages
Art-direction and responsive images
Using srcset to optimize image loading
Using the heights and sizes attributes
Adding a related articles section with thumbnail images
Using CSS3 flexbox for layout in AMP
Scaling up for larger screens
Using flex and media queries for horizontal layout
Using responsive images and srcset to deliver high quality images on all screen sizes
Using element media queries to display art-directed images
Using flex-item layout
Horizontal flex items
Vertical flex items
Full width flex item container
Flex items with specific proportions
Mixing flex and non-flex items
Using placeholders and fallbacks to improve user experience
Placeholders
Fallbacks
Using custom CSS in AMP pages
Adding custom fonts to AMP pages
Using custom fonts to improve page design
Text layout with CSS and HTML
Text layout with <amp-fit-text>
Adding SVG graphics to AMP pages
Summary
Engaging Users with Interactive AMP Components
Building collapsible content with <amp-accordion>
Building an expandable top stories category list
Styling <amp-accordion>
Improving the accordion with an expanded state indicator
It's accordions all the way down!
Building navigation menus
Horizontal navigation menus
Scrollable horizontal navigation
Building a navigation menu with <amp-carousel>
Adding side navigation with <amp-sidebar>
Triggering the sidebar
Styling the sidebar with CSS
Adding an SVG hamburger menu button
A note on accessibility
Hierarchical navigation menus with <amp-sidebar> and <amp-accordion>
Scaling up
Implementing tabbed content with <amp-selector>
Displaying user notifications
Using server endpoints to store the dismissal state of user notifications
The Action and Event model in AMP
Attaching event handlers with the on attribute
Events and actions
Handling multiple events on a single element
Triggering multiple actions for a single event
Using actions on any HTML element
Summary
Building Rich Media Pages in AMP
Showcasing products with <amp-carousel>
Building a carousel of products
Hero promotion with <amp-carousel> slides
Autoplaying <amp-carousel> slides
Adding call-to-action text to carousel images
Building a product image gallery
Product image gallery with thumbnail previews
Jumping to a specific image with goToSlide()
Highlighting the selected thumbnail
Reducing code with <amp-selector>
Adding video to AMP pages
Hosting your own videos with <amp-video>
Embedding hosted videos
Adding audio to AMP pages
Embedding self-hosted audio with <amp-audio>
Embedding third-party hosted audio
Showcasing your products with <amp-lightbox>
Lightboxing product images
Closing the lightbox
Using social media in AMP pages
Promoting products with social media
Setting default share text
Improving product SEO with metadata
Using tabs in product pages
Summary
Making Contact - Forms in AMP
Using forms in AMP
Submitting forms in AMP
A simple newsletter sign-up form
Submitting XHR AJAX forms in AMP
Handling XHR responses with <amp-mustache>
Creating the server in PHP
Hiding the form on success
Custom form validation
UX improvement - visual feedback on submission
Building a product search form
Styling the search form
The server response - a JSON list of products
Iterating over JSON data with <amp-mustache>
Showing the search status
Animating the search icon
A caveat with the submit-success approach
Implementing a shopping cart in AMP
Variable substitution in AMP
Using CLIENT_ID to identify a shopping cart
Building the shopping cart server
Handling the shopping cart server response
Dismissing the cart summary
Redirecting after form submission
Summary
Dynamic Content and Data-Driven Interaction
Dynamic content - fetching JSON data on page load
The <amp-list> component
Fetching a list of related products with <amp-list>
Using list tags <ul> and <li> with <amp-list>
A note on <amp-list> container size
Fetching the shopping cart on page load
Showing the cart contents with <amp-mustache>
Sharing a mustache template between <amp-list> and <amp-form>
Removing items from the cart
Retrieving URL parameters with AMP's variable substitution
Live content updates with <amp-live-list>
Using <amp-live-list>
A simple <amp-live-list> example
A live Twitter search listing
Adding a search form to use with <amp-live-list>
Why is it more complicated with the AMP Cache?
Implementing a live leaderboard
Summary
Programming in AMP - amp-bind
Introducing <amp-bind>
State, expressions, and data-binding
Stateful data in <amp-bind> with <amp-state>
Initializing state with <amp-state>
Updating state with AMP.setState()
Debugging state with AMP.printState()
Expressions in <amp-bind>
Text manipulation expression
Arithmetic expression
Branching if...else expression
Data-binding: linking expressions to element state
Using <amp-bind>
Changing text with <amp-bind>
Setting default values for AMP state properties
Changing CSS class with <amp-bind>
Removing cart items with <amp-bind>
User-triggered updates with <amp-list> and <amp-bind>
Ensuring that <amp-list> has a unique URL
Improving search with <amp-list> and <amp-bind>
Sorting, filtering, and updating search results
Using amp-list to show search results
Search results JSON response
Filtering by color, and sorting by price
Adding search autosuggest
Improving the product image carousel with <amp-bind>
Configuring product options with <amp-bind>
Product configuration: basic version
Choosing options with <amp-selector> and <amp-bind>
Binding selection options to the shopping cart
Product configuration: advanced version
Initializing product data with <amp-state>
Creating the product carousels
Adding a size option
Using <amp-selector> for image preview thumbnails
Keeping the thumbnails preview option in sync
Keeping track of chosen options and price in the cart
Summary
When AMP Is Not Enough - Enter the iframe
The <amp-iframe> component
What about the risk to performance?
Restrictions on <amp-iframe>
Configuring the iframe
iframe resizing
Google Maps in AMP
Getting a Google Maps Embed API key
Using the Google Maps Embed API
Fullscreen maps
Other features of the Google Maps Embed API
Centering a map on a place name
Centering a map on a lat/lng location
Showing directions and routes
Searching for a location
Map search with <amp-form> and server backend
Map search without server backend
Geolocating the users device
Using the Google Maps JavaScript API
Building the map
Using the HTML5 Geolocation API
Serving iframe content from a different domain
Adding the iframe map content to the AMP page
Showing a route from the current location
Disqus comments in AMP
Configuring Disqus for your site
Resizing the iframe
Adding the Disqus <amp-iframe>
Building a checkout process with the Payment Request API
The HTML5 Payment Request API
Using the Payment Request API with <amp-iframe>
Preparing the payment request
Summary
Ads and Analytics in AMP
Analytics support in AMP
Pixel tracking with <amp-pixel>
Full analytics tracking with <amp-analytics>
Configuring <amp-analytics>
Requests
Variables
Triggers
Loading configuration remotely
Transport configuration
Using amp-analytics with built-in vendors
Using Google Analytics with <amp-analytics>
Click and tap tracking
Variable substitution in <amp-analytics>
Tracking outbound link clicks
Scroll tracking
Tracking time on a page with timer triggers
Tracking social interaction
Analytics for e-commerce
Tracking the addition of items to the cart
Tracking the removal of items from the cart
Session stitching AMP Cache and original domain
Session stitching with Google Tag Manager
Ads in AMP
The <amp-ad> component
Embedding an Adsense ad
Ad placement
Ad placeholder
Ad fallback
Sticky ads
Getting creative with ads
Carousel ads
Flying carpet ads
Summary
AMP Deployment and Your Web Presence
Canonical AMP pages
Progressive Web Apps and AMP
PWA minimum requirements
What is a service worker?
What is a web app manifest?
Adding a PWA to the home screen
AMP and PWAs - three approaches
AMP as PWA
Installing a service worker with AMP
Writing a service worker to cache resources
Injecting JavaScript with a service worker
AMP to PWA
Caching PWA assets with a service worker
Installing a service worker from the AMP Cache
The service worker iframe installer
The PWA page
AMP in PWA
Loading AMP with Shadow AMP
Navigating within the PWA
Navigation and the HTML5 History API
Serving AMP pages to all mobile visitors
Using device detection to serve AMP
AMP and WordPress
Summary
AMP - Where It's At and Where It's Going
From zero to AMP
Keeping up with AMP - the AMP roadmap
Contributing
AMP - from web pages to web apps
User-friendliness
The AMP Cache
Flexibility
Criticism of AMP
AMP Cache URL
The DNS solution
AMP lightning badge of trust in search results
De facto SEO benefits of the AMP carousel
Summary
AMP Components
Ads and analytics
Dynamic content
Layout
Media
Presentation
Third-party media
Actions and Events
Events
Actions
amp-bind Whitelisted Functions
JavaScript whitelisted functions
amp-bind Permitted Attribute Bindings
Why did I write this book? Back in 2006, I was working with a company called dotMobi. I had the wonderful opportunity of working with some super-smart people--Ronan Cremin, Jo Rabin, and James Pearce--who were trying to make the mobile web happen (every year, according to James, was going to be the year of the mobile web, until 2008, when it eventually was).
One of the things that the team at dotMobi was doing was working with the W3C to help draft the Mobile Web Best Practices (MWBPs). We had already built the mobiReady mobile web checker, and the W3C was building its own Mobile Web Best Practices checker that, with my experiences with mobiReady under my belt, I was able to help out with. It was around this time, too, that we launched mobiForge; this was an educational site for web developers getting into mobile web development.
The point of all these initiatives? To give web developers and site owners the tools and knowledge they needed to build sites that performed acceptably under the constraints of the devices and cell networks of the day. This was 10 years ago, pre-iPhone, and the challenges for mobile web developers were considerable. Slow devices, slow networks, and small screens were the order of the day.
When the AMP project was launched, the similarities with the W3C MWBPs struck a chord with me. For one thing, the general goal was the same: follow good development practices, make the mobile web faster, and deliver a better user experience. However, even more than this, the AMP restrictions echoed very much the MWBPs, and the rules we'd built into mobiReady, even if some of the exact details had changed during the intervening 10 years. These were things like not using JavaScript, limiting the number of external resources and HTTP requests, and keeping the page size down. I could be talking about AMP, or the MWBPs.
So, AMP was a project I could identify with, even if some parts of it (such as the AMP cache URLs) are controversial, and I embraced what--as Alex Russell described it at the first AMP conference--has become "the most successful component library in the world." I understand the criticisms of the project, but coming from a background where web performance and user experience goals are important, I believe that, right now, the benefits outweigh the drawbacks.
Even without the cache, AMP is a fast, easy-to-use, and versatile component library. I hope that this book will help you see it the way I do.
Chapter 1, Ride the Lightning with AMP, introduces AMP, why it's needed, and what it brings to the mobile web. It describes how performance affects user behavior on the web, and its effect on conversions. It explains, at a high level, how AMP solves the problem of performance. Basic AMP concepts are introduced, and AMP boilerplate code is demonstrated in this chapter.
Chapter 2, Building Your First AMP Page, builds on the boilerplate code from the last chapter. The reader will see how to build a simple blog/article content page, while highlighting the similarities and differences between AMP-HTML and regular HTML. It demonstrates what happens when you use HTML tags that aren't allowed, to introduce AMP validation. The reader will learn how to develop and debug AMP pages, making use of the AMP validator and browser console as indispensable tools. Also, custom elements are introduced in the chapter.
Chapter 3, Making an Impression - Layout and Page Design in AMP, improves on the article-style page we built in the last chapter. The reader will learn about layout support and responsive design in AMP, and styling using CSS.
Chapter 4, Engaging Users with Interactive AMP Components, looks at how to deliver better user experiences via enhanced interaction mechanisms available in AMP. Building upon the prototype from the previous chapters, the reader will learn how to develop a side-drawer navigation menu, collapsible accordion content containers, and dismissible user notifications, as well as other techniques designed to make the most of limited screen space on mobile devices.
Chapter 5, Building Rich Media Pages in AMP, shows how to add rich media to AMP pages by building out an e-commerce product page prototype, which includes product image galleries and lightboxes, as well as audio and video components.
Chapter 6, Making Contact - Forms in AMP, shows what support there is for forms and form submission in AMP. A signup form, a product search form, and a basic shopping cart are developed that will demonstrate client-side validation and error handling, as well as how to build an endpoint to process form submissions.
Chapter 7, Dynamic Content and Data-Driven Interaction, explains how to automatically populate AMP pages with data retrieved by the JSON API. The product page is improved by dynamically adding related content data retrieved this way, and the shopping cart is enhanced to allow removal of items.
Chapter 8, Programming in AMP - amp-bind, introduces a programming paradigm offered in AMP via the amp-bind component.
Chapter 9, When AMP Is Not Enough - Enter the iframe, talks about workarounds for the limitations imposed by AMP. While it provides many custom elements to provide extended behavior, there are times when AMP can't provide the functionality you need. In these cases, the desired behavior can often be achieved with iframes, using amp-iframe.
Chapter 10, Ads and Analytics in AMP, introduces the reader to the different ways in which ads can be integrated into AMP pages. Different ad types and styles are reviewed and implemented. Analytics solutions are also implemented, demonstrating how to track user visits and other trackable events.
Chapter 11, AMP Deployment and Your Web Presence, outlines a number of options to deploy your AMP pages, whether standalone or as part of a bigger web presence.
Chapter 12, AMP - Where It's at and Where It's Going, reflects on what has been achieved. It covers the recent and under-development features in AMP, and where the project is going.
Appendix A, AMP Components, provides a reference list of all AMP components.
Appendix B, Actions and Events, provides a reference list of actions and events that can be used for interactions in your AMP pages.
Appendix C, amp-bind Whitelisted Functions, provides a reference list of whitelisted JavaScript functions that can be used in amp-bind expressions
Appendix D, amp-bind Permitted Attribute Bindings, provides a reference of element attributes that support data binding
The requirements for this book are straightforward for AMP, and are similar for every chapter:
Webserver such as Apache, NGINX, or NodeJS
Web browser (such as Chrome or Firefox)
Text/HTML editor (such as SublimeText)
A web-connected mobile device, such as an Android or iOS phone, is recommended but not required
Additionally, some examples require the following. Where required, this is noted along with the example:
HTTPS.
Server-side technology--some examples require a server-side component to deliver data. PHP was chosen for its wide availability, but any server-side language could be used.
Access to an alternative domain--this can simply be a domain alias that points to the same application directory on your server. For example, some files must be accessible at
example.com
, and another part of the example must be available at
alt.example.com
.
This book is for experienced web developers who are seeking to serve content to their end users in a rich and enticing way using Accelerated Mobile Pages. You need to be familiar with HTML5, CSS3, JavaScript, and JSON, and be aware of the impact of slow-loading web pages and performance on conversion rates and user engagement.
In this book, you will find a number of text styles that distinguish between different kinds of information. Here are some examples of these styles and an explanation of their meaning.
Code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles are shown as follows: "Just add<meta charset="utf-8">immediately after the opening<head>tag."
A block of code is set as follows:
<script async src="https://cdn.ampproject.org/v0.js"></script>
Any command-line input or output is written as follows:
npm install -g amphtml-validator
New terms and important words are shown in bold. Words that you see on the screen, for example, in menus or dialog boxes, appear in the text like this: "Select System info from the Administration panel."
Feedback from our readers is always welcome. Let us know what you think about this book-what you liked or disliked. Reader feedback is important for us as it helps us develop titles that you will really get the most out of.
To send us general feedback, simply e-mail [email protected], and mention the book's title in the subject of your message.
If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, see our author guide at www.packtpub.com/authors.
Now that you are the proud owner of a Packt book, we have a number of things to help you to get the most from your purchase.
You can download the example code files for this book from your account at http://www.packtpub.com. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you.
You can download the code files by following these steps:
Log in or register to our website using your e-mail address and password.
Hover the mouse pointer on the
SUPPORT
tab at the top.
Click on
Code Downloads & Errata
.
Enter the name of the book in the
Search
box.
Select the book for which you're looking to download the code files.
Choose from the drop-down menu where you purchased this book from.
Click on
Code Download
.
Once the file is downloaded, please make sure that you unzip or extract the folder using the latest version of:
WinRAR / 7-Zip for Windows
Zipeg / iZip / UnRarX for Mac
7-Zip / PeaZip for Linux
The code bundle for the book is also hosted on GitHub at https://github.com/PacktPublishing/AMP-Building-Accelerated-Mobile-Pages. We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing/. Check them out!
We also provide you with a PDF file that has color images of the screenshots/diagrams used in this book. The color images will help you better understand the changes in the output. You can download this file from https://www.packtpub.com/sites/default/files/downloads/AMPBuildingAcceleratedMobilePages_ColorImages.pdf.
Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you find a mistake in one of our books-maybe a mistake in the text or the code-we would be grateful if you could report this to us. By doing so, you can save other readers from frustration and help us improve subsequent versions of this book. If you find any errata, please report them by visiting http://www.packtpub.com/submit-errata, selecting your book, clicking on the Errata Submission Form link, and entering the details of your errata. Once your errata are verified, your submission will be accepted and the errata will be uploaded to our website or added to any list of existing errata under the Errata section of that title.
To view the previously submitted errata, go to https://www.packtpub.com/books/content/support and enter the name of the book in the search field. The required information will appear under the Errata section.
Piracy of copyrighted material on the Internet is an ongoing problem across all media. At Packt, we take the protection of our copyright and licenses very seriously. If you come across any illegal copies of our works in any form on the Internet, please provide us with the location address or website name immediately so that we can pursue a remedy.
Please contact us at [email protected] with a link to the suspected pirated material.
We appreciate your help in protecting our authors and our ability to bring you valuable content.
If you have a problem with any aspect of this book, you can contact us at [email protected], and we will do our best to address the problem.
Web performance is 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
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.
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!)
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.
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?
A steady stream of data has surfaced over the past few years that highlights the correlation of performance with user engagement. For example:
Walmart found that each one second decrease in page load time resulted in a 2 percent increase in conversions (
slideshare.net/devonauerswald/walmart-pagespeedslide
)
Amazon reported that a 100 ms increase in latency resulted in a 1 percent reduction in sales (
blog.gigaspaces.com/amazon-found-every-100ms-of-latency-cost-them-1-in-sales/
)
Barack Obama's US presidential campaign saw a 14 percent increase in donations with a 60 percent increase in site speed (
kylerush.net/blog/meet-the-obama-campaigns-250-million-fundraising-platform
)
Google found that a half second longer search page generation time caused traffic to drop by 20 percent (
glinden.blogspot.gr/2006/11/marissa-mayer-at-web-20.html
)
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.
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.
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 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.
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 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 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.
