jQuery / Plugin / jquery.mb.YTPlayer — YouTube動画を背景にする

jquery.mb.YTPlayerはYouTube動画をページ全体または指定要素の背景に配置するプラグインです。完全版jQueryとプラグインのCSS・JavaScriptを読み、高さのある要素で.YTPlayer()を呼びます。再生できなくても本文と操作を使えるよう、静止背景も用意します。

ファイルと実行条件

開発者の導入文書ではHTTPサーバーが必要で、file://とjQuery slimは対象外です。この例は完全版3.7.1とプラグイン3.4.6を固定します。パッケージ情報の依存範囲もjQuery 3.xです。4への変更はファイル名だけで済ませず、プラグインとの互換性を別に確認します。

順番はjQuery、プラグイン、初期化です。CSSも含めます。WordPressでテーマが既にjQueryを提供している場合、本文に二つ目を足すのではなく登録スクリプトの依存関係を管理します。以下は独立した練習用HTMLです。

要素を背景にする完全な例

UTF-8のytplayer-demo.htmlとして保存します。IDはYouTube API文書の例です。実際には利用権限と埋め込み許可が適切な動画を選びます。説明と操作は装飾領域の外にあります。

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>YouTube background with a static alternative</title>
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jquery.mb.YTPlayer/3.4.6/css/jquery.mb.YTPlayer.min.css">
  <script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.mb.YTPlayer/3.4.6/jquery.mb.YTPlayer.min.js"></script>
  <style>
    body { font: 16px/1.6 sans-serif; max-width: 900px; margin: 20px; }
    #video { width: 100% !important; height: 340px !important; padding: 0 !important; overflow: hidden; position: relative; background: linear-gradient(120deg,#164e63,#0f766e); }
    button { font: inherit; margin: 4px; }
    #status { overflow-wrap: anywhere; }
  </style>
</head>
<body>
  <h1>A background is optional</h1>
  <p>This text remains readable without video. Loading connects to YouTube.</p>
  <button type="button" id="load">Load YouTube background</button>
  <button type="button" id="play" disabled>Play</button>
  <button type="button" id="pause" disabled>Pause</button>
  <button type="button" id="static">Static background / reload</button>
  <p id="status" role="status">Static background; video not requested.</p>
  <div id="video" aria-hidden="true"></div>
  <p>Keep important content and controls outside this decorative region.</p>
  <script>
    document.querySelector("#static").addEventListener("click", function () { location.reload(); });
    document.querySelector("#load").addEventListener("click", function () {
      const status = document.querySelector("#status");
      if (window.matchMedia("(prefers-reduced-motion: reduce)").matches) {
        status.textContent = "Reduced motion: keeping the static background."; return;
      }
      if (!window.jQuery || typeof jQuery.fn.YTPlayer !== "function") {
        status.textContent = "Dependency unavailable; keeping the static background."; return;
      }
      this.disabled = true;
      status.textContent = "Loading; playback is not yet confirmed.";
      const $video = jQuery("#video");
      const timer = setTimeout(function () {
        status.textContent = "Still waiting; use Static background / reload if needed.";
      }, 15000);
      $video.on("YTPPlay", function () {
        clearTimeout(timer); status.textContent = "Playing muted background.";
        jQuery("#pause").prop("disabled", false);
      }).on("YTPPause", function () {
        status.textContent = "Paused."; jQuery("#pause").prop("disabled", true);
      });
      $video.YTPlayer({
        videoURL: "M7lc1UVf-VE", containment: "self", ratio: "16/9",
        autoPlay: true, mute: true, loop: true, showControls: false,
        useOnMobile: false, useNoCookie: true, gaTrack: false,
        stopMovieOnBlur: true,
        onReady: function () {
          clearTimeout(timer); status.textContent = "Player ready; use Play if playback does not start.";
          jQuery("#play").prop("disabled", false);
        },
        onError: function (player, error) {
          clearTimeout(timer);
          status.textContent = "YouTube error " + error.data + "; use Static background / reload.";
        }
      });
      jQuery("#play").on("click", function () { $video.YTPPlay(); });
      jQuery("#pause").on("click", function () { $video.YTPPause(); });
    });
  </script>
</body>
</html>

初期表示ではYouTube動画を要求しません。ただしjQueryとプラグインのCDNファイルはページ表示時に読み込みます。

Static background; video not requested.

PythonがあればファイルのフォルダーでPowerShellを開き、次を実行します。他のHTTPサーバーでも構いません。8000が使用中なら空きポートに変更します。

python -m http.server 8000 --bind 127.0.0.1
  1. ダブルクリックではなくhttp://127.0.0.1:8000/ytplayer-demo.htmlへアクセスします。
  2. Load YouTube backgroundで外部接続と準備を始めます。
  3. 実際の再生イベントでPlaying muted background.となりPauseが有効になります。準備完了だけでは再生成功ではありません。
  4. 準備後に動かなければPlayを試します。Pauseは一時停止で、ネットワークや埋め込み制限を解決する操作ではありません。
  5. Static background / reloadは文書全体を再読込し、以前の動画と要求を終了して初期状態に戻します。他の練習状態も戻ります。
  6. サーバー終了は端末でCtrl+Cです。

Windows Edge・jQuery 3.7.1で実プラグインの初期化、外部要求を遮断した待機、依存ファイル失敗、動きの軽減と再読込を確認しました。映像のストリーミング成功は別に判断する必要があり、全機種での再生を保証しません。

オプションと状態を区別する

containment="self"は選択要素を使います。高さ0では見えないため幅100%・高さ340px・padding=0を!importantで指定し、プラグインのインライン寸法と比率用余白より優先しました。bodyはページ全体になり重なりも検討が必要です。まず限定領域で確認します。16:9を狭い領域へ充填すると切れる部分があるため重要情報を背景だけに置きません。

mute=trueは消音、loop=trueは繰り返し、autoPlay=trueは準備後の再生試行です。自動再生ポリシー、iframe権限、端末条件で結果は変わります。onReadyと実再生のYTPPlayを分けています。15秒の文言は待機でありエラーの断定ではありません。

useOnMobile=falseではプラグインがモバイルと判断した環境で背景動画を使わずグラデーションを残します。狭いPC画面は実機検証の代わりではありません。Load時に動きの軽減がreduceなら初期化しませんが、開始後の設定変更までは監視しません。

useNoCookie=trueはyoutube-nocookie.comを使う設定で、外部接続やデータ処理がなくなる意味ではありません。ボタンは接続時点を明確にします。サイトのプライバシー案内と設定は実際の運用に合わせます。

失敗とサービスの制約

空白ならNetworkで依存ファイルとYouTube要求を、Consoleで最初のエラーを確認します。拡張機能、ネットワーク、Content Security Policyも点検します。API自体が来なければonErrorも動かない場合があり、待機案内と静止画への復帰が必要です。

IFrame APIエラー文書では100は削除・非公開など利用不可、101・150は埋め込み禁止、153はHTTP Refererなどのクライアント識別がない要求です。no-referrerを解決策として追加せず、サーバー・WebView・ブラウザーの実際の要求を調べます。

showControlsはプラグインの操作UIで、広告やYouTube表示を全て消す保証ではありません。現在のプレーヤーパラメーターにはmodestbrandingなどの廃止も示されています。quality=highresで最高画質を必ず強制できるとは考えません。

動画がなくてもメニューや本文を使えるようにします。視聴が理解に必須なら装飾背景ではなく、字幕や説明を備えた操作可能な通常プレーヤーが適しています。