Lazy load Youtube Video Iframe

Cách ngăn chặn tải youtube video trong iframe và những tài nguyên bên thứ 3 phục vụ cho việc play video.

Tại sao không được nhúng mã video youtube trực tiếp ở dạng iframe?

Mã nhúng youtube chiếm tới ~500 KB (gzipped) bao gồm các files đi kèm. Trong đó javascript chiếm 85%. Điều này sẽ khiến hiển thị ảnh thumbnail video của bạn chậm hơn (minh chứng). Trên thiết bị mobile, nó cũng sẽ ảnh hưởng xấu đến tốc độ tải các phần khác của trang.

Không phải tất cả khách truy cập vào trang của bạn đều sẽ phát video. Do đó, các tệp sẽ được tải sau trong iframe video youtube khi người dùng nhấp vào nút play. Bài viết này sẽ hướng dẫn bạn tối ưu tải các files khi nhúng video youtube/vimeo. Giả sử, bạn có mã nhúng youtube iframe như sau:

<iframe style="max-width:100%" width="560" height="315" src="https://www.youtube.com/embed/e1gAyQuIFQo" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>

Sửa lại mã nhúng iframe để không bị tải trước.

Một cách dễ dàng để ngăn đoạn mã iframe tải tệp là:

  • Dùng thuộc tính `data-src` thay vì `src`
  • Thêm thuộc tính class & id cho iframe để trì hoãn load javascript.
  • Thêm css `display:none` để ẩn đi ban đầu.
<iframe style="max-width:100%;display:none;" id="youtube-embed-iframe" width="560" height="315" data-src="https://www.youtube.com/embed/e1gAyQuIFQo" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>

Tạo thumbnail cho video.

Một cách đơn giản để trích xuất thumbnail của video youtube, sử dụng cấu trúc URL https://img.youtube.com/vi/{video-id}/mqdefault.jpg. Chúng ta cần thêm liên kết cho ảnh thumbnail này và nút play hiển thị phía trên hình ảnh, khi người dùng nhấn nút sẽ load mã nhúng video.

<style>
  .youtube {
      position: relative;
      display: inline-block;
  }
  .youtube:before {
      content: "";
      position: absolute;
      width: 100%;
      height: 100%;
      z-index: 10;
      background-size: 30%;
      background: transparent url('url_for_play_button.svg') center center no-repeat;
  }
  </style>

<a href="javascript:void(0);" onclick="showVideo();" id="youtube-link" class="youtube" >
	<img id="youtube-thumb" src="https://img.youtube.com/vi/e1gAyQuIFQo/mqdefault.jpg" width="560" style="max-width:100%" alt="{ video title }" />
</a>

Với đoạn code trên, chúng ta mới tạo ra cách hiển thị video ở dạng hình ảnh. Bước tiếp đến, sẽ thêm chức năng javascript để tải video khi người dùng nhấn nút play (thông qua hàm showVideo()).

Thêm hành động load và play Youtube video

Mã javascript dưới đây, có tạo hàm showVideo() để sử lý:

  • ẩn thumbnail
  • Hiển thị mã nhúng iframe youtube và thiết lập thuộc tính src.
  • Nạp Youtube iframe api, để có thể tự động chơi video.
<script>
  var player;
  function onYouTubeIframeAPIReady() {
      player = new YT.Player('youtube-embed-iframe', {
        height: '315',
        width: '560',
        videoId: 'e1gAyQuIFQo',
        events: {
          'onReady': onPlayerReady,
        }
      });
  }
  
  function onPlayerReady(event) {
          console.log('player ready');
      event.target.playVideo();
  }
  
  
  function stopVideo() {
      player.stopVideo();
  }
  
  function showVideo()
  {
          document.getElementById('youtube-link').style.display = "none";
          document.getElementById('youtube-embed-iframe').style.display="block";
          document.getElementById('youtube-thumb').style.display="none";
          let ifr = document.getElementById('youtube-embed-iframe');
          ifr.setAttribute('src',ifr.getAttribute('data-src'))
          var tag = document.createElement('script');
          tag.src = "https://www.youtube.com/iframe_api";
          var firstScriptTag = document.getElementsByTagName('script')[0];
          firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
  }
  </script>

Xem demo.

0 0 đánh giá
Đánh giá bài viết
Theo dõi
Thông báo của
guest

0 Góp ý
Phản hồi nội tuyến
Xem tất cả bình luận
0
Rất thích suy nghĩ của bạn, hãy bình luận.x