Mixing Dynamic and Cached Data

Edit on Github
Open in Playground

Mixing Dynamic and Cached Data

This is a sample showing how to implement product data details such as description, price, availability etc. AMPs can be served from the AMP Cache. Due to the AMP Cache's stale-while-invalide caching strategy, one user will see stale data until the latest version has been fetched. This might be a problem if product data needs always to be up-to-date, for example, product availability. This sample demonstrates how to avoid stale data on cached AMPs.

Setup

Additionally used AMP components must be imported in the header. We use amp-list for retrieving latest data from the server.

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

We use amp-mustache as a templating for amp-list

<script async custom-template="amp-mustache" src="https://cdn.ampproject.org/v0/amp-mustache-0.1.js"></script>

How to implement dynamic and cached product data details

To ensure that users always see the latest content, you can use the amp-list component which will fetch and render content directly from your server.

Example

<amp-list height="24"
  layout="fixed-height"
  src="/json/product.json"
  class="m1">
  <template type="amp-mustache">
    Price: ${{price}}
  </template>
</amp-list>

For product details such a descriptionb or title, where are unlikely to change frequently, you don't need to use amp-list

Example

An awesome product

<p> An awesome product </p>

if you need to make multiple calls to get all the data, that is not a problem in AMP since if multiple amp-list with the same src are found in the page, only one network call is actually made by the AMP runtime. By checking the network tab of the Chrome dev console, you can check that this second amp-list does not cause a second network call. Since we are using a service-worker you may see two similar calls one after the other to the same endpoint, so to better verify this behaviour, go to Application -> Service workers and click on Unregister.

Example

<amp-list height="24"
  layout="fixed-height"
  src="/json/product.json"
  class="m1">
  <template type="amp-mustache">
    Availability: {{availability}}
  </template>
</amp-list>