LoginSignup
31
31

More than 5 years have passed since last update.

YouTube動画の埋め込みを軽くする

Posted at

YouTube動画の埋め込みコード。
サイトに複数貼り付けると重い。でも貼り付けたい。
そんな埋め込みコードを、自動でサムネイル画像に置換することで軽くする方法です。
JavaScript(jQuery)を使用します。

軽くする方法

基本はこちらの記事のコードを使用させていただきました。
http://qiita.com/yuyaonrails/items/5ecb24fca0d54abccdab

それに加えて、

  • widthとheightも取得する
  • 動画埋め込みオプションの「動画が終わったら関連動画を表示する」をOFFにする(URLパラメータが加わるので上記コードだとサムネイルが取得できない)
  • サムネイルにYouTube公式のアイコンを付けて、通常の埋め込みと同じような見た目にする

コード

HTML
<!-- YouTubeの埋め込みコードをdivで囲む(複数貼り付ける時も動画1つずつ囲む) -->
<div class="youtube">
<iframe width="320" height="180" src="https://www.youtube.com/embed/動画ID?rel=0" frameborder="0" allowfullscreen></iframe>
</div>
CSS
.youtube {position:relative;}/* ラッパー */
.youtube_play:hover {cursor:pointer;}/* サムネイル */
.youtube_btn {/* YouTubeアイコン */
/* アイコンの画像とサイズ指定 */
width:42px;
height:30px;
background-image:url(マウスが乗っていない.png);
/* 上下左右中央へ配置 */
position:absolute;
top:0;
bottom:0;
left:0;
right:0;
margin:auto;
}

JavaScript
$(function (){
 var movies = [];
 var movies_w = [];
 var movies_h = [];
 var images = [];

 $('.youtube iframe').each(function(index, element) {
      //属性を取得
      var movie_src = $(this).attr('src');
      var movie_width = $(this).attr('width');
      var movie_height = $(this).attr('height');
      //配列へ
      movies[index] = movie_src
      movies_w[index] = movie_width
      movies_h[index] = movie_height
      //サムネイルを取得(この場合は320x180)
      images[index] = 'http://i.ytimg.com/vi' + movie_src.substring(movie_src.lastIndexOf("/"),movie_src.lastIndexOf("?")) + '/mqdefault.jpg'
      //置き換え
      $(this).after('<div class="youtube_play"><img src="' + images[index] + '" width="' + movies_w[index] + '"><div class="youtube_btn"></div></div>').remove();
 });

 $('.youtube_play').each(function(index, element) {
      $(this).click(function(){
      //クリックで置き換え
      $(this).after('<iframe src="' + movies[index] + '&amp;autoplay=1" width="' + movies_w[index] + '" height="' + movies_h[index] + '" frameborder="0"></iframe>').remove();
      });
      $(this).hover(function(){
      //ロールオーバー
      $(".youtube_btn").eq([index]).css("background-image","url(マウスが乗っている.png)");
      },function(){
      $(".youtube_btn").eq([index]).css("background-image","");
      });
 });
});

YouTubeアイコン

こちらからダウンロードできる
https://www.youtube.com/yt/brand/ja/downloads.html

注意

  • URLパラメータ無しの場合はコード修正が必要
  • スマホの場合、自動再生が不可能なので2回タップしないと再生できない
31
31
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
31
31