混合動態與快取資料
簡介
這個範例示範如何整合產品資料詳細資訊,例如產品說明、價格、供應狀況等,並滿足不同的資料即時性需求。AMP 可以從 AMP 快取提供。由於 AMP 快取的「過時失效重新驗證」快取策略,使用者可能會看到過時的資料,直到擷取到最新版本為止。如果產品資料必須隨時保持在最新狀態 (例如產品供應狀況),這可能會是個問題。這個範例示範如何避免在快取的 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,您可能會看到兩個類似的呼叫,前後呼叫相同的端點。為了更妥善地驗證這個行為,請前往「應用程式」 -> 「Service Worker」,然後按一下「取消註冊」。
<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