Issues

AMP up your Website with Umbraco

More and more users are turning to their mobile devices to consume web content. In fact, in 2015, Google announced that “more Google searches take place on mobile devices than on computers in 10 countries including the US and Japan”. As a result of this boom in mobile utilization, we as developers have to be increasingly mindful of these increasing group of users.

Data shows that 40% of people will abandon a website that takes more than three seconds to load.

Too often we forget that not everyone is surfing the web at a wired internet connection speed. Often people are using these mobile devices in places where coverage can be spotty. Data shows that 40% of people will abandon a website that takes more than three seconds to load. That could be a lot of missed conversions for your company or client! As usual, Google has an answer, and it is called Accelerated Mobile Pages (AMP).

What is AMP?

Google defines AMP as “AMP, or Accelerated Mobile Pages, are lightweight webpages consisting of stripped down HTML (AMP HTML), a streamlined version of CSS, and AMP JS which, though limited, allows pages to load asynchronously”. That was a lot to take in at once! Let's break down what they mean.

Stripped Down HTML

First, there is the AMP HTML. This is normal HTML with some restrictions which promote reliable performance and some AMP specific extensions for building rich content beyond basic HTML. Some normal elements like the <img/> tag are replaced with AMP versions to allow the page to load asynchronously. These custom tags keep AMP in control of the layout and loading of resources to give the best experience to the user.

Streamlined CSS

Next there is the streamlined version of CSS. When a CSS file comes from an external source, it can block the rendering of a page. This especially is a problem for slower connects which can result in a flash of unstyled content (FOUC). For this reason, AMP requires that all CSS be placed inline in the head of the document. Also, the inline CSS cannot be bigger than 50kb to guide the page author to only put the styles that are required for that page to render. Though this might seem like a huge limitation, the size is large enough to create a sophisticated page.

AMP Javascript

Finally, there is AMP JS. This library automatically manages the resource loading of the page and also provides the custom AMP HTML tags. This all comes together to help to provide quick rendering of a page to the browser. As a result, all 3rd party JavaScript is only allowed in the iframes tags that the AMP JS provides. Some elements on the page must also define their size attributes. This allows AMP JS to discern what the page will look like before the assets are loaded and it can layout the page in advance. AMP JS also controls the resource load chain automatically to prioritize certain items over others. An example of this is prioritizing image assets that appear in the viewport above the fold. Among the biggest optimizations is the fact that it forces everything that comes from external sources to load asynchronous. This safeguards that nothing in the page can block another from rendering.

Why Should I Care?

If you’re a HTML wizard and have poured your life into making your website the most sleekest streamlined one out there, then AMP probably isn’t for you. For the rest of us, AMP provides a strict guideline to create mobile experiences that can load quickly on any device no matter what the connection. The built in AMP validation ensures that developers stay in the fast lane when creating AMP pages and provides instant feedback to what is wrong.

With AMP, content is king and the user experience is queen. This might sound bad at first, until you realize that fast content, leads to faster reading, leads to more consumption. More content shown to a user allows for greater opportunities to convert those users to your ultimate goals.

With AMP, content is king and the user experience is queen.

Google is pushing developers to use AMP pages in a similar fashion as they propelled creating mobile friendly pages. Sometime in the future, AMP pages might actually be used as a ranking factor when conducting searches on mobile devices. Google sees mobile as being the future of search, and this is one initiative that will push to improve the user experience of their results and hopefully decrease bounce rates for the publisher as a result. AMP pages also provide an opportunity for the content to appear in Google’s mobile search result carousel at the top of results.

By opting in to using AMP HTML pages, you will also be able to leverage the Google AMP Cache. The Google AMP Cache is a proxy based content delivery network, which will deliver your pages and resources closer to the user geographically. The Google AMP Cache will automatically go and fetch your document, JS files, and images to be cached, thus improving the performance and speed of delivery to the end user.

I’m convinced, sign me up

Luckily the barrier to entry into the AMP world is quite low. AMP HTML is merely HTML with some restrictions and extras. What this means is that, for developers, it is easy to pick up and start running with. It also does not require any complicated build processes to create AMP pages. Therefore it can be easily mixed in with view engines like Razor which Umbraco leverages.

Here is an example of how an amp page looks.

<!doctype html>
<html amp lang="en">
  <head>
    <meta charset="utf-8">
    <script async src="https://cdn.ampproject.org/v0.js"></script>
    <title>Hello, AMPs</title>
    <link rel="canonical" href="http://example.ampproject.org/article-metadata.html" />
    <meta name="viewport" content="width=device-width,minimum-scale=1,initial-scale=1">
    <script type="application/ld+json">
      {
        "@context": "http://schema.org",
        "@type": "NewsArticle",
        "headline": "Open-source framework for publishing content",
        "datePublished": "2015-10-07T12:02:41Z",
        "image": [
          "logo.jpg"
        ]
      }
    </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>
  </head>
  <body>
    <h1>Welcome to the mobile web</h1>
  </body>
</html>

The boilerplate above gives you all the things that an AMP page must have to be valid. In addition, that boilerplate includes optional meta-data in the form of JSON-LD. This json style schema tells web crawlers information about the page and is a requirement if you want the content to appear in places like the Google Search news carousel.

With a little razor sugar, we can convert that boilerplate into a reusable Razor layout.

@inherits UmbracoTemplatePage
<!doctype html>
<html amp lang="en">
  <head>
    <meta charset="utf-8">
    <script async src="https://cdn.ampproject.org/v0.js"></script>
    <title>@Model.Content.Name | Company Name</title>
    <link rel="canonical" href="@(Umbraco.NiceUrlWithDomain(Model.Content.Id))" />
    <meta name="viewport" content="width=device-width,minimum-scale=1,initial-scale=1">
    @RenderSection("Schema", false)
    <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>
    @RenderSection("CustomCss", false)
  </head>
<body>
    @RenderBody()
</body>
</html>

From the boilerplate, all of the static content has been stripped out and been replaced by sections that can optionally be rendered to the page. This includes the schema which was discussed above, the custom CSS that should be used on the page, and finally the body of the page which has been replaced by @RenderBody().

Now we are ready to create our first AMP template for some content. In this basic example, the Umbraco content has both a image property and an RTE for the body content. We have also created a image crop for the hero images so that they are a consistent size named “Banner Small”.

@inherits UmbracoTemplatePage<Basic>
@{
    var heroImage = Umbraco.TypedMedia(Model.Content.HeroImage);
}
<amp-img src="@heroImage.GetCropUrl("Banner Small")"
         width="640"
         height="480"
         layout="responsive">
</amp-img>

<h1>@Model.Content.Name</h1>

@Model.Content.Body

A couple of interesting things to note here. First is that we are not using the standard img tag. Instead we are using amp-img instead. Using this tag gives the amp runtime full control over that image element. The runtime can choose to delay or prioritize loading the resource based on a number of factors including viewport position and connection bandwidth. This is true for many other of the amp elements that have a standard HTML counterpart and allow the load time of the page to be perceived as instant.  

Another notable addition is the fact that the image size is explicitly set in the tag. This gives the AMP runtime the dimensions of the resource in order to layout the page and remove the need to re-render and to do additional layout calculations which can slow down the browser. Even though we are specifying the exact dimensions of the image, that doesn’t mean we cannot have responsive layouts. By adding the “layout=’responsive’” attribute to the element, AMP knows to size it the width to the container element and set the height automatically based on the aspect ratio.

As you are creating AMP pages, they will begin to come more and more complex much like a regular HTML page. Using Razor, you can template out common elements just as you would your normal HTML sites and most of the tricks you have learned will translate nicely.

Ensuring AMP Best Practices

How do you make sure you are following all of the AMP guidelines? Google has implemented a handy trick to validate your AMP HTML markup within the browser. By appending “#development=1” to the end of an AMP HTML url, the runtime will validate your markup to ensure you are following all of the AMP requirements. If a validation error occurs, it will show in the development console of the browser. A detailed error message will be shown there, and even a link to the documentation of the validation in question is embedded as a url into the error. There is also a web interface validator which shows the errors inline alongside the HTML at validator.ampproject.org. It is very important to check the validation after creating your pages and editing them. If your AMP page is not valid, the AMP page will not be discovered or distributed by third party websites.

You now have the basic building blocks to create AMP pages within Umbraco! Check out the AMP project website to get the latest documentation on AMP HTML. To learn more about AMP in Umbraco and how to have AMP pages live alongside your normal HTML pages, come check out my session at uWestFest this March.

Alex Vilmur

Alex joined Marcel Digital in 2014 to focus on web and consumer facing applications. He has developed multiple extensions for the Umbraco CMS that have focused on increasing SEO visibility. Alex studied Computer Science in Indiana at Purdue University and previously worked at Motorola in the Government and Public Safety division.

comments powered by Disqus