包含 iframe
了解如何在页面中显示媒体内容,以及如何使用 iframe 来显示 AMP 限制之外的高级内容。
基础知识
您可以使用 amp-iframe
元素在页面中显示 iframe。
在 AMP 中,iframe 特别适用于显示主页面上下文中不支持的内容,例如需要用户编写 JavaScript 的内容。
amp-iframe
的要求
- 必须至少距离顶部 600px 或第一个视口的 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 Map
<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
包含一个带有 placeholder
属性的元素(例如,amp-img
元素),则可以在文档顶部显示 amp-iframe
,该元素将在 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 示例中找到更高级的 amp-iframe
示例。