Created
February 2, 2016 22:44
-
-
Save selwynpolit/8fa47e1c4d57105f2739 to your computer and use it in GitHub Desktop.
gtm video tracker
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<script type="text/javascript"> | |
// This code loads the IFrame Player API code asynchronously. | |
(function GtmVideoTracker(){ | |
var tag = document.createElement('script'); | |
var firstScriptTag = document.getElementsByTagName('script')[0]; | |
window.GTMplayers = window.GTMplayers || []; | |
tag.src = "https://www.youtube.com/iframe_api"; | |
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag); | |
// Optional: Enable JS API if it is not already on the URL | |
for(var p = document.getElementsByTagName('iframe'), i = p.length, r = /youtube\.com\/embed/; i--;) { | |
if (r.test(p[i].src)) { | |
if (p[i].src.indexOf('enablejsapi') === -1) { | |
p[i].src += (p[i].src.indexOf('?') === -1 ? '?' : '&') + 'enablejsapi=1'; | |
} | |
} | |
} | |
window.onYouTubeIframeAPIReady = window.onYouTubeIframeAPIReady || function() { | |
for(var p = document.getElementsByTagName('iframe'), i = p.length, r = /youtube\.com\/embed/; i--;) { | |
if (r.test(p[i].src)) { | |
window.GTMplayers.push(new YT.Player(p[i], { | |
events: { | |
'onReady': onPlayerReady, | |
'onStateChange': onPlayerStateChange | |
} | |
})); | |
} | |
} | |
}; | |
window.onPlayerReady = window.onYouTubeIframeAPIReady || function(){ | |
window.playerReady = true; | |
}; | |
/** | |
// The API calls this function when the player's state changes. | |
window.onPlayerStateChange = window.onPlayerStateChange || function (event) { | |
// do stuff here | |
} | |
*/ | |
})(); | |
</script> | |
<script src="//dpp750yjcl65g.cloudfront.net/analyticsengine/dist/video/beta/youtube-raw.js"></script> | |
<script> | |
(function(w,n,a){w[n]=w[n]||function(){return(w[n][a]=w[n][a]||[]).push(arguments)}}(window, 'videoTracking', 'c')); | |
if (typeof window.videoTracking == 'function') { | |
window.videoTracking(function(tracking) { | |
//tracking.progress(10, 'percent'); | |
tracking.datalayer('dataLayer'); | |
var z = setInterval(function() { | |
if (window.GTMplayers) { | |
if (window.playerReady) { | |
clearInterval(z); | |
for(i = 0, len = window.GTMplayers.length; i < len; i++) { | |
tracking.player(window.GTMplayers[i]); | |
} | |
} | |
} else if (window.players) { | |
if (jQuery('.video-disabled').length < 1) { | |
clearInterval(z); | |
for(var _player in window.players) { | |
var obj = window.players[_player]; | |
tracking.player(obj); | |
} | |
} | |
} | |
}, 300); | |
}); | |
</script> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Here's a brief refactoring showing how I'd write the second bit as a function that immediately executes: