How to Use amp-img and amp-video to Speed Up Your Website

AMP, in a nutshell, is a method for optimizing websites to be faster and more performant.

AMP stands for "Accelerated Mobile Pages", and while the stated focus is performance on mobile devices, the speed gains it can bring are just as helpful on non-mobile devices. AMP contains a suite of optimization methods that offer various types of perks, but the power to make sites faster is arguably most significant on image and video-heavy sites.

Given faster sites make for more engaged visitors, potentially higher search engine rankings (and hence greater exposure), it's definitely worth thinking about AMP when you create the next web-based showcase of your work.

AMP is an open source project with Google behind it, and has now been in development since around September 2015, with AMP versions of sites appearing in Google search results since February 24th this year. We've been covering AMP since its public launch earlier this year, so it's a great idea to have a read of "AMP Project: Will it Make Your Sites Faster" if you'd like some background before we move on.

In that article you'll find a lot of information on the overall value of working with AMP, but we're going to look a bit more directly at the two most relevant aspects to working with images and video:  AMP's custom <amp-img> and <amp-video> elements.

Lighthouse at sunset
Lighthouse by ssuaphoto/PhotoDune. AMP can help your sites perform better in search.

What Are <amp-img> and <amp-video>?

When you create a page according to AMP requirements you'll use a series of custom elements instead of some of the default HTML elements you might be used to.

  • Instead of using a regular <img> element you'll use <amp-img>
  • Instead of using a <video> element you'll use <amp-video>

When you use these custom elements you'll automatically tap into some of the benefits inherent to AMP. Let's look at what they are and why they're worthy of your consideration.

Why Use <amp-img> and <amp-video>?

You already know that AMP is supposed to help make your sites faster, but what specifically do the <amp-img> and <amp-video> elements have to offer? The benefits that are most pertinent are as follows.

Lazy Loading

By default, if you have a page with several images on it, every single image has to be loaded in one hit. This can very easily drag your site's overall load time out to quite a duration. The higher your initial load time the more likely you are to have visitors abandon your site, and the worse you may do in search engines.

However with a technique called a "Lazy Loading", you can instead have just the first few images loaded with the rest to come later. Enough content is loaded for the visitor to start viewing the page, and the remaining images are "lazy loaded" when the visitor scrolls down. This can make considerable improvements to your load speed.

For example, in the tests I ran as part of my article "AMP Project: Will it Make Your Sites Faster", I found that on a simulated mobile connection it took 26 seconds to load a page with five 500Kb images. With an AMP version of the same site the load time was pared down to 16 seconds.

No Layout Reflow

One of the major perks of using AMP is it avoids the issue of having the page layout "reflow" multiple times. 

While a page is being served, the elements of unloaded media initially have no height or width. Hence the browser lays things out as though said media was not a part of the page. Then when an image finishes loading the layout has to be recalculated, with other elements moved and resized to fit around the image—something called reflowing. If other media is also yet to load the page has to reflow again and again for each item.

On mobile devices in particular, visitors can face frustration if they are already engaged and what they're focused on suddenly jumps out of sight due to reflow. This can very easily lead to reduced visitor attention or site abandonment, especially if it happens multiple times.

With AMP, reflow never occurs. This is because every piece of media has a correctly sized placeholder added into the layout from word go. Once the media is loaded it replaces the placeholder, no reflow necessary.

Free CDN Access

Storage and bandwidth for large amounts of media can become expensive fairly quickly, and choosing a host who can deliver quickly to viewers all over the world is not always easy.

When you use AMP however, you get access to a CDN provided by Google free of charge. As long as you create a page that passes AMP validation, Google will automatically cache your HTML documents, JS files and images in the AMP CDN.

Relatively Hands Free

The truth is most of the things AMP does for you can also be done in other ways via various scripts and methodologies. However one of the huge upsides to using AMP is you don't need to get intimately acquainted with the technicalities that go into setting up equivalent optimizations.

By using AMP you can avoid manually choosing, configuring and maintaining multiple scripts and processes. Instead you just use AMP as prescribed and everything happens in the background without needing your hands-on involvement.

Getting Started with AMP

Before we get into the specifics of using <amp-img> and <amp-video> you'll need to know how to create an AMP page with the required boilerplate code. We covered how to do this in another tutorial so to get the ball rolling you can head over to "How to Make a Basic AMP Page From Scratch".

There's no need to do the full tutorial, so if you just work through until the end of the section titled "Dealing with Inline CSS" you'll be all set to come back and pick up again here.

How to Use <amp-img>

On an AMP page you'll be using <amp-img> to load every single image. Let's go through how to use its code correctly and what each of its associated attributes do.

(You can find the full documentation for <amp-img> at the AMP project reference website).

Essential Inclusions

When adding an <amp-img> element there are a few essential attributes you'll need to include. As with a regular <img> element you'll need to use a src attribute to specify the location of your image, and an alt attribute to set a text fallback.

It is also a requirement in AMP that you specify height and width each time. This is because AMP uses the height and width attributes to set the size of placeholders before the image is loaded.

If you're concerned about how to make images behave responsively given you're setting fixed dimensions, don't worry because AMP has functionality included to handle responsive adjustments, which we'll touch on later.

A basic example of the <amp-img> element with these essential inclusions is:

Using srcset

The <amp-img> element provides a srcset attribute that can be used to specify alternate images to be displayed either at different widths or pixel densities. 

It's used the same way as in a regular <img> element, so you can get a full run down on the attribute at: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/img#attr-srcset

For example, to provide different images at different pixel densities you might use:

Or to load different images depending on viewport width you might use:

Note, if you are using values containing w the src attribute will be ignored in browsers that support srcset.

Adding Attribution

If you need to give credit for to an image you can use attribution, for example:

Styling Placeholders

If you'd like to control the appearance of the placeholders that appear in your page while images are loading you can do so with CSS targeted at the amp-img element, for example:

How to Use <amp-video>

In an AMP page you'll use <amp-video> whenever you want to embed a video from your own source. If you're looking to embed third party video, such as from YouTube or via an iFrame, you can instead use other elements like <amp-youtube> or <amp-iframe>.

(Again, you can find the full documentation for <amp-video> at the AMP project reference website).

Essential Inclusions

As with <amp-img>, there are a few essential inclusions when using <amp-video>. Once again src is required to specify the location of the video, and both height and width are required so AMP can correctly lay out the page while loading.

A basic example with required attributes might be:

Adding a Fallback

In case the video doesn't load or display for one reason or another, it's possible to setup a fallback by nesting a <div> inside the <amp-video> element. The <div> should include the attribute fallback.

For example:

Adding Multiple Sources

The <source> element can be nested inside the <amp-video> element to provide multiple file formats and maximize the probability of compatibility in various browsers.

This works in the same way it does in a regular HTML5 <video> element so for full details check out: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/source

As an example:

Setting a "Poster"

Before playback on a video has started the first frame of the video will be displayed by default. However if you want to customize what is shown you can specify an image using the attribute poster.

For example:

Extra Attributes

As well as what we've discussed above, there are a few extra attributes you can use with the <amp-video> element. They are as follows.

Autoplay

By default videos won't play automatically. To override this include the attribute autoplay:

Controls

Controls on a video won't appear unless you add the attribute controls:

Loop

To make a video repeat infinitely include the attribute loop:

Muted

To turn off the sound on a video add the attribute muted:

The "layout" Attribute

AMP's <amp-img> and <amp-video> elements can have the attribute layout set to one of six values, each of which makes the element behave differently:

  • responsive
  • fill
  • fixed
  • fixed-height
  • flex-item
  • nodisplay

Let's take a quick look at what each one does.

(Find the complete layout docs here: https://github.com/ampproject/amphtml/blob/master/spec/amp-html-layout.md)

responsive

Your "go to" layout setting should be responsive in most cases - use this if you're not sure what to choose. It will cause the element to expand to the maximum width of its parent element while maintaining its aspect ratio.

The ability to add this attribute is why you don't have to worry about ensuring responsiveness despite setting explicit height and width values on elements.

fill

The fill setting is almost the same as responsive, however the element will expand to both the maximum width and height of its parent, regardless of aspect ratio.

fixed

Using a fixed layout will keep the element at its specified height and width with no ability to resize.

fixed-height

With the fixed-height setting an element will stretch its width to fit the parent element but keep its height the same. 

flex-item

If you've applied the CSS display: flex; to an element's parent, you can use the flex-item layout value to make it fill all available space inside the parent element. If multiple children of the same parent use the flex-item layout they will share space equally.

nodisplay

The nodisplay setting is used to hide an element. It's purpose is to allow content to be shown upon a user's action, such as in conjunction with the <amp-lightbox> element.

Wrapping Up

That covers all the essentials of working with AMP's custom <amp-img> and <amp-video> elements, from why you should use them through to how.

AMP provides a consolidated, hands free way to optimize media heavy sites that makes for a much better mobile experience, while improving the desktop experience at the same time.

For more information check out the links below.

Related Links:

Tags:

Comments

Related Articles