いつも使ってたプラグインjQuery tubularと、解析タグが衝突を起こして不定期にバグが起きる症状に悩まされたので、自分で背景スクリプトを書いてみました。
jQuery1.8.3で動作しますが、それ以前でも以後でも動く気はします。
html
bodyの開始タグの直後がおすすめ
<div id="bg">
<div id="bgPlayer"></div>
<div class="overlay"></div>
</div>
css
#bg{
width: 100%;
height: 100%;
z-index: 1;
position: fixed;
overflow: hidden;
left: 0;
top: 0;
}
#bgPlayer{
position: absolute;
}
.overlay{
width: 100%;
height: 100%;
z-index: 2;
position: fixed;
left: 0;
top: 0;
}
JavaScript
var tag = document.createElement('script');
tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
var player;
function onYouTubeIframeAPIReady() {
player = new YT.Player('bgPlayer', {
height: '315',
width: '560',
videoId: '2bJ49dOSP9o',
playerVars: { 'autoplay': 1,
'controls': 0,
'showinfo': 0,
'rel' : 0,
'modestbranding': 1,
'loop': 1,
'playlist': '2bJ49dOSP9o',
'wmode': 'transparent'
},
events: {
'onReady': onPlayerReady,
}
});
}
function onPlayerReady(event) {
event.target.mute();
event.target.playVideo();
}
$(function(){
var ratio = 16/9;
$('html,body').css({'width': '100%', 'height': '100%'});
function setSize(){
var width = $(window).width(),
pWidth,
height = $(window).height(),
pHeight,
$bgPlayer = $('#bgPlayer');
if (width / ratio < height) {
pWidth = Math.ceil(height * ratio);
$bgPlayer.width(pWidth).height(height).css({left: (width - pWidth) / 2, top: 0});
} else {
pHeight = Math.ceil(width / ratio);
$bgPlayer.width(width).height(pHeight).css({left: 0, top: (height - pHeight) / 2});
}
}
setSize();
$(window).resize(function() {
setSize();
});
});
参考サイト
jQuery tubular
http://www.seanmccambridge.com/tubular/
YouTube JavaScript Player API Reference
https://developers.google.com/youtube/js_api_reference?hl=ja
YouTube 埋め込みプレーヤーとプレーヤーのパラメータ
https://developers.google.com/youtube/player_parameters?hl=ja