Click on image to play lazy load embedded Youtube video

需求

  1. 蓋一層 placeholder image
  2. 點擊 play button 可自動播放影片 (*手機無法自動播放)
  3. 影片結束後會自動重播
  4. 盡可能少露出 Youtube 相關的品牌資訊 (*無法完全 100% 移除)

我的原始碼

<div class="hero__video">
  <div class="hero__video-wrapper" id="youtube" data-embed="88Ft83XvkSY">
    <div class="hero__play-btn"></div>
    <img src="../images/hero_video_placeholder.jpg" class="hero__video-placeholder preload" />
  </div>
</div>
const createYoutubeIframe = () => {
  const youtube = document.getElementById('youtube');

  youtube.addEventListener('click', (e) => {
    const wrapper = e.currentTarget;
    const iframe = document.createElement('iframe');
    const videoId = youtube.dataset.embed;
    const url = `https://www.youtube.com/embed/${videoId}?autoplay=1&amp;loop=1&amp;showinfo=0&amp;modestbranding=1&amp;rel=0&amp;playlist=${videoId}`;

    iframe.setAttribute('allow', 'autoplay');
    iframe.setAttribute('allowfullscreen', 1);
    iframe.setAttribute('src', url);
    wrapper.innerHTML = '';
    wrapper.appendChild(iframe);
  })
}

export default createYoutubeIframe;

預覽畫面

相關閱讀

1個讚