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>,即可使用這個元件。