What is the AMP

At the forefront of Google’s AMP “Accelerated Mobile Pages” technology, we can dramatically improve the user experience of entering our Pages from the search engine.

An AMP

AMP HTML

AMP HTML is essentially HTML extended with custom AMP attributes. The simplest AMP HTML file looks like this:


      
<html⚡ >
 <head>
   <meta charset="utf-8">
   <link rel="canonical" href="hello-world.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>
   <script async src="https://cdn.ampproject.org/v0.js"></script>
 </head>
 <body>Hello World!</body>
</html>
Copy the code

AMP pages are found through HTML tags by search engines and other platforms with .

AMP JS

The AMP JS library implements all of AMP’s best performance practices, manages resource loading, and gives you the custom tags mentioned above, all to ensure fast rendering of your web pages.

One of the most significant optimizations is that it allows all content from external sources to remain asynchronous, allowing any content in a web page to render without hindrance.

Other performance techniques include sandboxing all iframes, pre-calculating the layout of each element on a web page before loading resources, and disabling slow CSS selectors.

AMP Cache

AMP cache is a proxy-based content delivery network (CDN) for delivering valid AMP documents. AMP cache is designed to:

  1. Only valid AMP pages are provided.
  2. AMP web pages can be preloaded safely and efficiently.
  3. Implement additional performance tuning measures on the content to improve the user experience.

Who requests cached AMP pages?

Cached AMP pages are accessed by various platforms (such as Google Search, Google News, and Cloudflare) and mobile apps. Mobile applications can associate cached AMP content through a web address (see Google’s AMP URL API) or through cross-source XHR in progressive Web applications (see embedding AMP Pages and using them as data sources for details).

How to do that?

The platform can find your AMP content through the < HTML ⚡> or < HTML AMP > tag and cache that content. For example, Google search crawls content; Any page that has been identified as a valid AMP will be automatically added to the Google AMP cache.

The benefits of the AMP

  1. Rapid loading
  2. Reduce page complexity
  3. Google search results pre-load AMP pages to get to pages faster

How does AMP improve performance

Only asynchronous scripts are allowed (to prevent blocking pages)

Since JavaScript also blocks DOM building and slows down page rendering, AMP only allows asynchronous JavaScript.

AMP pages cannot contain any JavaScript written by the author. Use custom AMP elements instead of JavaScript to handle interactive page functionality.

Exception: third-party JS is allowed in iframe, but it does not block rendering.

Statically size all resources (reduce page backflow)

External resources such as images, ads, or iframes must declare their size in HTML so that AMP can determine the size and location of each element before the resource is downloaded.

AMP loads the page layout without waiting for all resources to download.

AMP decouples the document layout from the resource layout. Laying out the entire document, including the fonts, requires only one HTTP request.

Because AMP is optimized to avoid costly style recalculations and layouts in the browser, there will be no relayouts when the resources load.

Don’t let extension mechanism block rendering (extension components don’t block rendering)

<script async custom-element="amp-iframe" src="https://cdn.ampproject.org/v0/amp-iframe-0.1.js"></script>
Copy the code

CSS must be embedded and have size limits (to reduce HTTP requests)

CSS blocks all rendering and page loading and tends to become bloated. In AMP HTML pages, only inline styles are allowed. Compared to most web pages, this restriction can remove one or more HTTP requests from the critical render path.

In addition, the inline style sheet is 50 KB at most. While this size is large enough for very complex pages, page authors still need to practice good CSS style.

Setting the priority of resource loading (lazy loading)

AMP controls all resource downloads: it prioritizes resource loading, loads only what is needed, and preextracts lazy-loaded resources.

When downloading resources, AMP optimizes the download to prioritize the most important resources currently available.

Images and ads only download when they are on the front screen and the user is likely to view them or scroll quickly to them.

AMP also preextracts resources with lazy loading features. Resources are loaded as late as possible, but preextracted as early as possible. This is very fast to load, but the CPU is only used when the resource is actually displayed to the user.

Instant loading page (pre-rendered first screen)

Make extensive use of the new PreConnect API to ensure HTTP requests are as fast as possible.

This way, a page can be rendered before the user explicitly indicates that they want to go to it; The page may be ready before the user actually selects it, enabling instantaneous loading.

All web content can be pre-rendered, but this process also requires some bandwidth and CPU usage. AMP has been optimized to reduce the consumption of both factors. Pre-render only downloads the first screen resources and does not render potentially CPU intensive resources.

When AMP documents are pre-rendered for instantaneous loading, only the first screen resources are actually downloaded.

When AMP documents are pre-rendered for instantaneous loading, resources (such as third-party iframes) that might use a lot of CPU are not downloaded.

How to develop AMP pages

  1. Create the page

    
            
    <html⚡ >
      <head>
        <meta charset="utf-8">
        <script async src="https://cdn.ampproject.org/v0.js"></script>
        <title>Hello AMP world</title>
        <link rel="canonical" href="hello-world.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>
        <h1>Hello AMP World!</h1>
      </body>
    </html>
    Copy the code
    • As document type<! doctype html>At the beginning
    • Contains the top⚡ < HTML >Tags (also accepted<html amp>)
    • contains<head><body>Tags (these tags are optional in HTML)
    • in<head>Contains a<link rel="canonical" href="$SOME_URL">Tag that points to the regular HTML version of an AMP HTML document, or to the document itself if such an HTML version does not exist
    • contains<meta charset="utf-8">Mark as<head>The first child of the tag
    • in<head>The tag contains<meta name="viewport" content="width=device-width,minimum-scale=1">The tag. Recommendations includeinitial-scale=1
    • contains<script async src="https://cdn.ampproject.org/v0.js"></script>Mark as<head>(Doing so will include and load the AMP JS library)
    • In its<head>The tag contains the following:
    <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>
    Copy the code
  2. Add a component to a web page

    <amp-img src="https://www.ampproject.org/examples/images/amp.jpg"
      width="900" height="508" layout="responsive"></amp-img>
    Copy the code
    <! -- this script is requiredfor amp-youtube and must be in the <head> section  -->
    <script async custom-element="amp-youtube"
          src="https://cdn.ampproject.org/v0/amp-youtube-0.1.js"></script>
    <amp-youtube data-videoid="9Cfxm7cikMY"
        layout="responsive"
        width="480" height="270"></amp-youtube>
    Copy the code
  3. Design Element Style

    To style elements on an AMP page, add CSS to the inline style sheet named

    <style amp-custom> amp-img {margin: 0.5em; } body { max-width: 900px; } </style>Copy the code
  4. Adding analysis Tools

<amp-analytics type="googleanalytics">
<script type="application/json">
{
  "vars": {
    "account": "UA-YYYY-Y"
  },
  "triggers": {
    "default pageview": {
      "on": "visible"."request": "pageview"."vars": {
        "title": "Name of the Article"
      }
    }
  }
}
</script>
</amp-analytics>
Copy the code
  1. Prepare the page for distribution

    In some cases, you may want to have both a non-AMP version and an AMP version of the same page (for example, a news article). Consider this: If A Google search finds a non-AMP version of the page, how does it know that the page has an AMP version?

    Double page:

    Add the following to a non-AMP page:

    <link rel="amphtml" href="https://www.example.com/url/to/amp/document.html">
    Copy the code

    Add the following to the AMP page

    <link rel="canonical" href="https://www.example.com/url/to/full/document.html">
    Copy the code

Single page:

If you only have one page, and that page is an AMP page, you still have to add a canonical link to it, which just points to itself:

<link rel="canonical" href="https://www.example.com/url/to/amp/document.html">
Copy the code

Some limitations of AMP

  1. ! importantQualifier Disallows the use of this qualifier. This is a requirement for AMP pages to be able to enforce their element sizing rules.
  2. < link rel = "stylesheet" >Prohibited, except for custom fonts.
  3. scriptThe label.application/ld+jsonExcept for more specification and restrictions on https://www.ampproject.org/zh_cn/docs/fundamentals/spec

Matters needing attention

  1. Handle cross-domain requests well

    Because the user may access your webpage from AMP Cache, the domain name may be a CDN domain name, there is a possibility of cross-domain. Need to do the configuration of a service at https://www.ampproject.org/zh_cn/docs/fundamentals/amp-cors-requests#verify-cors-header

    function assertCors(req, res, opt_validMethods, opt_exposeHeaders) {
     var unauthorized = 'Unauthorized Request';
     var origin;
     var allowedOrigins = [
        "https://example.com"."https://example-com.cdn.ampproject.org"."https://example.com.amp.cloudflare.com"."https://cdn.ampproject.org" ];
     var allowedSourceOrigin = "https://example.com";  //publisher's origin
     var sourceOrigin = req.query.__amp_source_origin;
    
     // If same origin
     if (req.headers['amp-same-origin'] = ='true') {
         origin = sourceOrigin;
     // If allowed CORS origin & allowed source origin
     } else if(allowedOrigins.indexOf(req.headers.origin) ! =- 1 &&
         sourceOrigin == allowedSourceOrigin) {
         origin = req.headers.origin;
     } else {
         res.statusCode = 401;
         res.end(JSON.stringify({message: unauthorized}));
         throw unauthorized;
     }
    
     res.setHeader('Access-Control-Allow-Credentials'.'true');
     res.setHeader('Access-Control-Allow-Origin', origin);
     res.setHeader('Access-Control-Expose-Headers'['AMP-Access-Control-Allow-Source-Origin']
             .concat(opt_exposeHeaders || []).join(', '));
     res.setHeader('AMP-Access-Control-Allow-Source-Origin', sourceOrigin);
    
    }
    Copy the code