混合動態與快取資料
簡介
這是一個範例,示範如何整合產品資料詳細資訊,例如描述、價格、供應狀況等,以及不同的資料新鮮度需求。AMP 可以從 AMP 快取提供。由於 AMP 快取的過時失效 (stale-while-invalid) 快取策略,在擷取到最新版本之前,使用者會看到過時的資料。如果產品資料需要始終保持最新狀態 (例如產品供應狀況),這可能會是個問題。此範例示範一種避免在快取 AMP 上出現過時資料的方法。
設定
我們使用 amp-list
從伺服器擷取最新資料。
<script async custom-element="amp-list" src="https://cdn.ampproject.org/v0/amp-list-0.1.js"></script>
我們使用 amp-mustache
作為 amp-list
的範本
<script async custom-template="amp-mustache" src="https://cdn.ampproject.org/v0/amp-mustache-0.2.js"></script>
如何實作動態與快取產品資料詳細資訊
對於產品詳細資訊,例如描述或標題,這些資訊不太可能經常變更,您不需要執行任何特殊操作。為了確保使用者始終看到最新的內容,您可以使用 amp-list
元件,它會直接從您的伺服器擷取並呈現內容。
我的產品
這真是一個很棒的產品。
<h3>My product</h3>
<p>This is a really great product.</p>
<amp-list height="24"
layout="fixed-height"
src="/static/samples/json/product.json"
binding="no">
<template type="amp-mustache">
Price: ${{price}}
</template>
</amp-list>
如果您需要多次呼叫才能取得所有資料,這在 AMP 中不是問題,因為如果在頁面中找到多個具有相同 src
的 amp-list
,則 AMP 執行階段實際上只會進行一次網路呼叫。
透過檢查 Chrome 開發人員工具的網路分頁,您可以檢查第二個 amp-list
是否不會導致第二次網路呼叫。
由於我們使用 service-worker,您可能會看到兩個相似的呼叫前後連接著同一個端點,因此為了更好地驗證此行為,請前往「Application」->「Service workers」,然後按一下「Unregister」。
<amp-list height="24"
layout="fixed-height"
src="/static/samples/json/product.json"
binding="no">
<template type="amp-mustache">
Availability: {{availability}}
</template>
</amp-list>
如果此頁面上的說明未涵蓋您的所有問題,請隨時與其他 AMP 使用者聯繫,討論您的確切使用案例。
前往 Stack Overflow 功能未說明?AMP 專案強烈鼓勵您的參與和貢獻!我們希望您能成為我們開放原始碼社群的持續參與者,但我們也歡迎您針對您特別感興趣的問題提供一次性貢獻。
在 GitHub 上編輯範例-
作者: @kul3r4