AMP

包含 iframe

瞭解如何在頁面中顯示媒體內容,以及如何使用 iframe 顯示 AMP 限制以外的進階內容。

基本概念

您可以使用 amp-iframe 元素在頁面中顯示 iframe。

在 AMP 中,iframe 特別適合用來顯示主要頁面內容中不支援的內容,例如需要使用者編寫 JavaScript 的內容。

amp-iframe 的需求

  • 必須距離頂端至少 600 像素 或第一個可視區域的 75% (使用 placeholder 的 iframe 除外)。
  • 只能透過 HTTPS 要求資源,而且除非未指定 allow-same-origin,否則不得與容器同源。

繼續閱讀 –amp-iframe 的完整規格中瞭解更多資訊。

包含指令碼

若要在頁面中包含 amp-iframe,請先在 <head> 中加入以下指令碼,這會載入擴充元件的額外程式碼

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

撰寫標記

在以下範例中,我們建立了一個回應式 amp-iframe,以透過 Google Maps Embed API 嵌入 Google 地圖

<amp-iframe width="200" height="100"
    sandbox="allow-scripts allow-same-origin"
    layout="responsive"
    src="https://www.google.com/maps/embed/v1/place?key={YOUR API KEY}&q=europe">
</amp-iframe>

使用預留位置

您可以在文件頂端顯示 amp-iframe,前提是 amp-iframe 包含具有 placeholder 屬性的元素 (例如,amp-img 元素),在 iframe 準備好顯示之前,該元素會呈現為預留位置。

繼續閱讀 –:在 具有預留位置的 Iframe 中瞭解更多關於預留位置的資訊。

具有預留位置的範例

<amp-iframe width="400" height="225"
    sandbox="allow-scripts allow-same-origin"
    layout="responsive"
    src="https://giphy.com/embed/OWabwoEn7ezug">
  <amp-img placeholder layout="fill"
      src="https://ampproject-b5f4c.firebaseapp.com/examples/images/kittens-biting.jpg"></amp-img>
</amp-iframe>

呈現為

範例

您可以在 AMP By Example 中找到更多進階的 amp-iframe 範例。