3
votes

The issue at hand is the embedding of multiple Youtube videos on a page and now the Youtube Analytics is not working. Previously I had many embedded videos on a Drupal page, but the site was not SEO friendly with the speed of the page being slow with many embedded Youtube videos making many calls back to Youtube site with js and css.

I found some good articles about speeding up the site by replacing the Youtube player with a placeholder image and when the user wishes to watch. I found the js code here (http://www.labnol.org/internet/light-youtube-embeds/27941/ and http://schoberg.net/2015/08/fast-agile-youtube-embed-responsive-iframe-load-delay-with-jquery/) With those "hacks" the website loads much faster and quicker and SEO score is higher.

Enter another problem. Now the Youtube analytics is not tracking the Youtube videos on the site anymore. I dont know why, the video still gets clicked on, and the embedded video does get played on the site.

What should I do with the embed code to make it track the Youtube video again?

How can I track it with Google Analytics if I cant track with Youtube Analytics anymore?

I need some StackOverflow magic...

The code to embed Youtube video on the page is:

<div class="youtube" id="_ynxddD0Eqk"></div>

and the function code on the backend:

    <script>
$(document).ready(function() {
  $(".youtube").each(function() {
    // Set the BG image from the youtube ID
    $(this).css('background-image', 'url(//i.ytimg.com/vi/' + this.id + '/hqdefault.jpg)');
    // Click the video div
    $(document).delegate('#' + this.id, 'click', function() {
      // Build embed URL
      var iframe_url = "//www.youtube.com/embed/" + this.id + "?autoplay=1&autohide=2&wmode=opaque&enablejsapi=1";
      // Grab extra parameters set on div
      if ($(this).data('params')) iframe_url += '&' + $(this).data('params');
      // Build iframe tag
      var iframe = $('<iframe/>', {'allowfullscreen':'allowfullscreen', 'frameborder': '0', 'src': iframe_url});
      // /youtube event tracking
      $(iframe).addClass("media-youtube-player");
      // Replace the YouTube thumbnail with YouTube HTML5 Player
      $(this).replaceWith(iframe);
    });// /click
  }); // /each video
}); // /document ready
 </script>
3

3 Answers

3
votes

Please take a look to how Komito Analytics does. See init_ function in the source code.

3
votes

I want to second the proposed solution with Komito Analytics.

Yes, it will be tracked with Google Analytics automatically. Just include the script as described at https://komito.net/integration/:

<script src="https://komito.net/komito.js"></script>

The documentation also reflects default configuration settings, please have a look on them and turn off not needed metrics.

0
votes

While I can't speak to the Youtube Analytics side of things, I can provide the code I wrote to capture data in Google Analytics for multiple Youtube iframe embeds on a page.

I use the class youtubeplayer on the iframes along with a unique ID for each (I generally just use the video title with hyphens).

<iframe id="the-video-title" class="youtubeplayer" width="560" height="315" src="https://www.youtube.com/embed/VIDEOIDHERE?wmode=transparent&enablejsapi=1&origin=SITEORIGINHERE&rel=0" frameborder="0" allowfullscreen></iframe>

Important parameters being enablejsapi and origin.

The following uses jQuery and requires the Youtube Data API to be enabled in your Google Developer Console.

//Check for Youtube Videos
function checkForYoutubeVideos(){
    if ( jQuery('.youtubeplayer').length ){
        players = {};
        var tag = document.createElement('script');
        tag.src = "https://www.youtube.com/iframe_api";
        var firstScriptTag = document.getElementsByTagName('script')[0];
        firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
    }
}
function onYouTubeIframeAPIReady(e){
    jQuery('iframe.youtubeplayer').each(function(i){
        var youtubeiframeClass = jQuery(this).attr('id');
        players[youtubeiframeClass] = new YT.Player(youtubeiframeClass, {
            events: {
                onReady: onPlayerReady,
                onStateChange: onPlayerStateChange,
                onError: onPlayerError
            }
        });
    });
    pauseFlag = false;
}
function onPlayerError(e){
    var videoTitle = e['target']['B']['videoData']['title'];
    ga('send', 'event', 'Error', 'Youtube API', videoTitle + ' (Code: ' + e.data + ')', {'nonInteraction': 1}); //Log the API error
}
function onPlayerReady(e){
   //Do something when player is ready.
}
function onPlayerStateChange(e){
    var videoTitle = e['target']['B']['videoData']['title'];
    if ( e.data == YT.PlayerState.PLAYING ){
        ga('send', 'event', 'Youtube', 'Play', videoTitle);
        pauseFlag = true;
    }
    if ( e.data == YT.PlayerState.ENDED ){
        ga('send', 'event', 'Youtube', 'Finished', videoTitle, {'nonInteraction': 1});
    } else if ( e.data == YT.PlayerState.PAUSED && pauseFlag ){
        ga('send', 'event', 'Youtube', 'Pause', videoTitle);
        pauseFlag = false;
    }
}

I typically also send custom dimensions, metrics, and timing data to Google Analytics too. For my full implementation, check out my Github file here.

This method should work with that custom "deferred" method of loading the videos that you mentioned, but you will definitely need to call my checkForYoutubeVideos() function after the lazyload has completed.