Easy Analytics For Your Embed Code Using Google Analytics

This is a tip which I was first introduced to by my friend Jonathan Kim of Appcues. If you have a SaaS tool which installs something onto a website, it’s likely you would like to know something about where it’s installed, how often it’s loaded, etc. You could build an analytics processing infrastructure like we have at Eager, but why not leverage the biggest, freest, analytics tool in the world: Google Analytics?

Cash Register

At its simplest, all you need to do is include the GA tracking snippet with your embed:

(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){ (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o), m=s.getElementsByTag ame(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m) })(window,document,'script','https://www.google-analytics.com/analytics.js','ga');

ga('create', 'UA-XXXXX-Y', 'auto');
ga('send', 'pageview');

Of course, many of your users may already use Google Analytics, there’s no reason to load the tracking code twice or accidentally send a second pageview event. Instead, lets check if it’s already being loaded first:

if (!window.ga){
  (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){  (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o), m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m) })(window,document,'script','https://www.google-analytics.com/analytics.js','ga');

ga('create', 'UA-XXXXX-Y', 'auto', {'name': 'myAwesomeEmbed'});
ga('myAwesomeEmbed.send', 'pageview');

You’ll also notice we are now giving our tracker a name, so it won’t conflict with a Google Analytics install already on the page.

Remember that you have all the power of Google Analytics. For example, you may want to track an event:

ga('myAwesomeEmbed.send', 'event', 'video', 'play', 'fallCampaign', 1);

Jonathan recommended another great use for this tracking capability: sending performance data from the browser. For example, you can include the timing information describing your script from the Performance API and get hard data on how long it takes to load on your user’s site:

if (window.performance && performance.getEntriesByType){
  var resources = performance.getEntriesByType("resource");

  for (var i=0; i < resources.length; i++){
    if (resources[i].name.indexOf('//my-awesome-site.com/my-script.js') !== -1){

      ga('myAwesomeEmbed.send', 'timing', 'Embed Code', 'scriptLoadTime', resources[i].duration);


Finally, it’s worth noting any analytics use introduces a privacy concern. We strongly recommend you inform your users of your use of analytics, and provide them with a method of opting out, or even better, ask them to explicitly opt-in.

Like this post? Share it with your followers.

Sign up to get our next post delivered to your inbox.

Follow us to get our latest updates.