iT邦幫忙

2019 iT 邦幫忙鐵人賽

DAY 24
0
Modern Web

AMP系列 第 24

AMP(Lession 24) - AMP 中的 iframe

AMP 中的 iframe

使用 amp-iframe 之前,有個極為重要的觀念一定要知道! amp-iframe 絕對不能主要用在顯示廣告上(請使用 amp-ad

Required Script

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

基本用法

<amp-iframe width="200" height="100"
    sandbox="allow-scripts allow-same-origin"
    layout="responsive"
    frameborder="0"
    src="https://www.google.com/maps/embed/v1/place?key=AIzaSyDG9YXIhKBhqclZizcSzJ0ROiE0qgVfwzI&q=iceland">
</amp-iframe>

Attribute

src

  • 行為主要類似於標準 <iframe>

  • srcdocframeborderallowfullscreenallowpaymentrequestallowtransparencyreferrerpolicy 這些屬性的行為應該與標準 <iframe> 的行為相同。

  • 如果未指定 frameborder ,則默認情況下,它將設置為0。

sandbox - sandbox 屬性,預設為為空值

common attributes

詳細請看

Iframe with placeholder

frame with a placeholder

<amp-iframe width=300 height=300
   layout="responsive"
   sandbox="allow-scripts allow-same-origin"
   src="https://foo.com/iframe">
 <amp-img layout="fill" src="https://foo.com/foo.png" placeholder></amp-img>
</amp-iframe>

我們可以看到,在 <amp-iframe> 裡還會有個 <amp-img> ;而這個 <amp-img> 一定會包含 placeholder 這個 attribute

frame embed-ready request

window.parent.postMessage({
  sentinel: 'amp',
  type: 'embed-ready'
}, '*');

Iframe resizing

  • 必須使用 resizable attribute 定義 amp-iframe
  • <amp-iframe> 必須具有溢出的子元素
  • <amp-iframe> 必須設置 allow-same-origin 這個 sandbox attribute。
  • iframe 文檔必須將嵌入大小請求作為窗口消息發送。
  • 如果請求高度小於某個閾值(100px),則將拒絕嵌入大小請求。
  • resizable 會使 scrolling 值為 no

Iframe viewability

可以向父視窗發送 send-intersections message;舉例來看:

window.parent.postMessage({
  sentinel: 'amp',
  type: 'send-intersections'
}, '*');

可監聽來自父視窗的 intersection message

window.addEventListener('message', function(event) {
  if (event.source != window.parent ||
      event.origin == window.location.origin ||
      !event.data ||
      event.data.sentinel != 'amp' ||
      event.data.type != 'intersection') {
    return;
  }
  event.data.changes.forEach(function (change) {
    console.log(change);
  });
});

參考來源:


上一篇
AMP(Lession 23) - 播放Youtube影片
下一篇
AMP(Lession 25) - 用 position observer 實現 scrolling 頁面時的一些互動效果
系列文
AMP30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言