加入圖片 & 影片
如同在一般的 HTML 頁面上一樣,AMP 可讓您嵌入圖片、影片和音訊內容。瞭解 AMP 等效元件的不同之處,並學習如何在您的頁面中加入這些元件。
為何不使用 <img>、<video> 和 <audio>?
AMP 不支援顯示媒體的預設 HTML 對應項目,例如 <img>
。我們提供對等元件的原因如下:
- 我們需要在資源載入前瞭解頁面的版面配置,這對於支援首頁預先載入至關重要
- 我們需要控制網路要求,以有效延遲載入和優先載入資源
圖片
使用 amp-img
元素在您的頁面中加入圖片,如下所示
<amp-img alt="A beautiful sunset"
src="/static/inline-examples/images/sunset.jpg"
width="264"
height="195">
</amp-img>
在這個最基本的範例中,圖片將以指定的固定高度和寬度顯示。至少需要設定明確的寬度和高度。
在 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>
進階版面配置
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>
行為和預留位置
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>
<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>
音訊
使用 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>
<script async custom-element="amp-audio" src="https://cdn.ampproject.org/v0/amp-audio-0.1.js"></script>
,即可使用此元件。