AMP

包含圖片和影片

就像在一般的 HTML 頁面上一樣,AMP 允許您嵌入圖片影片音訊內容。了解 AMP 等效元件的不同之處,並學習如何在您的頁面中包含它們。

為什麼不用 <img>、<video> 和 <audio>?

AMP 不支援用於顯示媒體的預設 HTML 對應項目,例如 <img>。我們提供等效元件的原因如下

雖然它們不受支援,但呈現,但 AMP 不會驗證您的頁面,而且您將無法獲得 AMP 提供的所有優勢。

圖片

使用 amp-img 元素在您的頁面中包含圖片,如下所示

<amp-img alt="A beautiful sunset"
  src="/static/inline-examples/images/sunset.jpg"
  width="264"
  height="195">
</amp-img>
在 playground 中開啟此程式碼片段

在這個最基本的範例中,圖片將以指定的固定高度和寬度顯示。至少需要設定明確的寬度和高度。

在 JavaScript 停用時顯示圖片

由於 <amp-img> 依賴 JavaScript,如果使用者選擇停用腳本,圖片將不會顯示。在這種情況下,您應該使用 <img><noscript> 為圖片提供後備方案,如下所示

<amp-img src="/static/inline-examples/images/sunset.jpg"
  width="264"
  height="195"
  alt="...">
  <noscript>
    <img src="/static/inline-examples/images/sunset.jpg" width="264" height="195" alt="...">
  </noscript>
</amp-img>
在 playground 中開啟此程式碼片段

進階版面配置

AMP 使建立完全響應式圖片比使用標準 CSS/HTML 容易得多。在其最基本的形式中,您只需新增 layout="responsive"

<amp-img alt="A view of the sea"
  src="/static/inline-examples/images/sea.jpg"
  width="900"
  height="675"
  layout="responsive">
</amp-img>
在 playground 中開啟此程式碼片段

繼續閱讀 – 深入了解進階版面配置技巧

行為和預留位置

AMP HTML 執行階段可以有效地管理圖片資源,根據視口位置、系統資源、連線頻寬或其他因素,選擇延遲或優先載入資源。

繼續閱讀 – 了解如何為圖片提供後備方案和預留位置

動畫圖片

amp-anim 元素與 amp-img 元素非常相似,並提供額外功能來管理動畫圖片(例如 GIF)的載入和播放。

<amp-anim width="400"
  height="300"
  src="/static/inline-examples/images/wavepool.gif"
  alt="...">
  <amp-img placeholder
    width="400"
    height="300"
    src="/static/inline-examples/images/wavepool.png"
    alt="...">
  </amp-img>
</amp-anim>
在 playground 中開啟此程式碼片段

注意 – 在頁面的 head 中包含 <script async custom-element="amp-anim" src="https://cdn.ampproject.org/v0/amp-anim-0.1.js"></script> 以使用此元件。

影片

使用 amp-video 元素在您的頁面中包含影片。

僅將此元素用於直接 HTML5 影片檔案嵌入。此元素會在 AMP 決定的時間延遲載入 src 屬性指定的影片資源。

在影片開始之前包含預留位置,並在瀏覽器不支援 HTML5 影片時包含後備方案,例如

此瀏覽器不支援 video 元素。

<amp-video controls
  width="640"
  height="360"
  src="/static/inline-examples/videos/kitten-playing.mp4"
  poster="/static/inline-examples/images/kitten-playing.png">
  <div fallback>
    <p>This browser does not support the video element.</p>
  </div>
</amp-video>
在 playground 中開啟此程式碼片段

音訊

使用 amp-audio 元素在您的頁面中包含音訊資源。

僅將此元素用於直接 HTML5 音訊檔案嵌入。與 AMP 頁面中的所有嵌入式外部資源一樣,此元素會在 AMP 決定的時間延遲載入 src 屬性指定的音訊資源。

在瀏覽器不支援 HTML5 音訊時包含後備方案,例如

您的瀏覽器不支援 HTML5 音訊。

<amp-audio width="400"
  height="200"
  src="/static/inline-examples/audio/cat-meow.mp3">
  <div fallback>
    <p>Your browser doesn’t support HTML5 audio.</p>
  </div>
  <source type="audio/mpeg"
    src="/static/inline-examples/audio/cat-meow.mp3">
  <source type="audio/ogg"
    src="/static/inline-examples/audio/cat-meow.ogg">
</amp-audio>
在 playground 中開啟此程式碼片段

注意 – 在頁面的 head 中包含 <script async custom-element="amp-audio" src="https://cdn.ampproject.org/v0/amp-audio-0.1.js"></script> 以使用此元件。