Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> JavaScript

Phát video lặp vô tận khi tải trang HTML5


Thuộc tính cơ bản

Sử dụng kết hợp 3 thuộc tính Boolean trên thẻ <video>:

  • autoplay: Tự động phát khi tải xong
  • loop: Lặp lại khi hết video
  • muted: Bắt buộc cho autoplay trên trình duyệt hiện đại (Chrome, Safari, Firefox chặn autoplay có âm thanh)

Code cơ bản

<video width="600" height="500" autoplay loop muted>
  <source src="movie.mp4" type="video/mp4">
  <source src="movie.webm" type="video/webm">
  <source src="movie.ogv" type="video/ogg">
  Trình duyệt của bạn không hỗ trợ video HTML5.
</video>

Ví dụ hoàn chỉnh với điều khiển

<!DOCTYPE html>
<html lang="vi">
<head>
  <meta charset="UTF-8">
  <title>Video Loop Background</title>
  <style>
    .video-container {
      position: relative;
      max-width: 800px;
      margin: 2rem auto;
    }
    .video-container video {
      width: 100%;
      height: auto;
      display: block;
    }
    .controls {
      margin-top: 1rem;
      display: flex;
      gap: 0.5rem;
    }
    button {
      padding: 0.5rem 1rem;
      background: #3498db;
      color: white;
      border: none;
      border-radius: 4px;
      cursor: pointer;
    }
    button:hover { background: #2980b9; }
    button:disabled { background: #bdc3c7; cursor: not-allowed; }
  </style>
</head>
<body>
  <div class="video-container">
    <video id="bgVideo" autoplay loop muted playsinline>
      <source src="background.mp4" type="video/mp4">
      <source src="background.webm" type="video/webm">
      Trình duyệt không hỗ trợ video HTML5.
    </video>
    
    <div class="controls">
      <button id="playPauseBtn" onclick="togglePlayPause()">Tạm dừng</button>
      <button id="muteBtn" onclick="toggleMute()">Tắt âm thanh</button>
      <button onclick="restartVideo()">Phát lại từ đầu</button>
    </div>
  </div>

  <script>
    const video = document.getElementById('bgVideo');
    const playPauseBtn = document.getElementById('playPauseBtn');
    const muteBtn = document.getElementById('muteBtn');
    
    function togglePlayPause() {
      if (video.paused) {
        video.play().catch(e => console.log('Autoplay bị chặn:', e));
        playPauseBtn.textContent = 'Tạm dừng';
      } else {
        video.pause();
        playPauseBtn.textContent = 'Phát';
      }
    }
    
    function toggleMute() {
      video.muted = !video.muted;
      muteBtn.textContent = video.muted ? 'Bật âm thanh' : 'Tắt âm thanh';
    }
    
    function restartVideo() {
      video.currentTime = 0;
      if (video.paused) video.play();
    }
    
    // Cập nhật nút khi video kết thúc (loop tự động nhưng có thể cần UI sync)
    video.addEventListener('ended', function() {
      // loop attribute tự xử lý, nhưng có thể thêm logic ở đây
    });
    
    // Xử lý lỗi autoplay
    video.addEventListener('play', function() {
      playPauseBtn.textContent = 'Tạm dừng';
    });
    video.addEventListener('pause', function() {
      playPauseBtn.textContent = 'Phát';
    });
  </script>
</body>
</html>

Video làm nền trang (Fullscreen Background)

<!DOCTYPE html>
<html lang="vi">
<head>
  <meta charset="UTF-8">
  <title>Video Background</title>
  <style>
    * { margin: 0; padding: 0; box-sizing: border-box; }
    
    #video-bg {
      position: fixed;
      top: 0; left: 0;
      width: 100%; height: 100%;
      object-fit: cover;        /* Crop để lấp đầy màn hình */
      z-index: -1;              /* Đằng sau nội dung */
    }
    
    .content {
      position: relative;
      z-index: 1;
      min-height: 100vh;
      display: flex;
      flex-direction: column;
      justify-content: center;
      align-items: center;
      color: white;
      text-align: center;
      padding: 2rem;
      background: rgba(0, 0, 0, 0.4); /* Overlay tối để chữ dễ đọc */
    }
    
    h1 { font-size: 3rem; text-shadow: 2px 2px 4px rgba(0,0,0,0.5); }
    p { font-size: 1.25rem; margin-top: 1rem; }
  </style>
</head>
<body>
  <video id="video-bg" autoplay loop muted playsinline>
    <source src="hero-bg.mp4" type="video/mp4">
    <source src="hero-bg.webm" type="video/webm">
  </video>
  
  <div class="content">
    <h1>Chào mừng đến với Website</h1>
    <p>Video nền lặp vô tận, tự động phát, tắt tiếng</p>
  </div>
</body>
</html>

Xử lý sự kiện ended (fallback nếu loop không hoạt động)

// Chỉ cần nếu loop attribute không hoạt động (hiếm)
video.addEventListener('ended', function() {
  video.currentTime = 0;
  video.play().catch(e => console.log('Replay failed:', e));
});

Lưu ý quan trọng về Autoplay Policy

Trình duyệtChính sách Autoplay
Chrome 66+Chỉ cho phép autoplay nếu muted hoặc user đã tương tác
Safari 11+Chỉ cho phép autoplay nếu muted + playsinline
Firefox 66+Cho phép autoplay muted, chặn autoplay có âm thanh
Edge 79+Giống Chrome (Chromium)

Luôn thêm muted và playsinline cho video background/autoplay.

Tối ưu hiệu năng

  • Dùng preload="metadata" (mặc định) hoặc "none" để không tải video ngay
  • Video nền nên ngắn (< 30s), nén tốt (H.264 High Profile, CRF 28-32)
  • Cung cấp cả WebM (VP9) và MP4 (H.264) cho hiệu năng tốt nhất
  • Dùng poster hiển thị ảnh chờ khi video tải