// enforced callback from Youtube = must be top-level
function onYouTubeIframeAPIReady() {
app.video.loadVideo('#myVideo');
}
app.video = (function() {
function init() {
// from https://developers.google.com/youtube/iframe_api_reference
// not: will not work in IE7 (postmessage)
// load API code
var tag = document.createElement('script');
tag.src = 'https://www.youtube.com/iframe_api';
document.body.appendChild(tag);
}
function loadVideo(container) {
var video = $(container);
var myVideo = new YT.Player(video.attr('id'), { // id of container
height: video.data('height'),
width: video.data('width'),
videoId: video.data('src'),
events:{
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
}
});
}
function onPlayerReady(event) {
// pass
}
function onPlayerStateChange(event) {
switch(event.data) {
case 1:
_gaq.push(['_trackEvent', 'My Video', 'Internal Link', 'Click to play ' + event.target.l.id]);
break;
case 2:
_gaq.push(['_trackEvent', 'My Video', 'Internal Link', 'Click to pause ' + event.target.l.id]);
break;
case 0:
_gaq.push(['_trackEvent', 'My Video', 'Internal Link', event.target.l.id + ' finished']);
break;
default:
break;
}
}
return {
init: init,
loadVideo: loadVideo
};
})();
Lazy load Youtube videos
Note: this post is 8 years old - code examples may need to be updated!