3

KISSMetrics sometimes causes trouble when loading on my site. Those familiar with it will probably know about the following snippet which appears in their docs:

<!-- Kissmetrics tracking snippet -->
<script type="text/javascript">var _kmq = _kmq || [];
var _kmk = _kmk || '61d817358af517ab2975dbb768eeb1d6d0d07c4b';
function _kms(u){
  setTimeout(function(){
    var d = document, f = d.getElementsByTagName('script')[0],
    s = d.createElement('script');
    s.type = 'text/javascript'; s.async = true; s.src = u;
    f.parentNode.insertBefore(s, f);
  }, 1);
}
_kms('//i.kissmetrics.com/i.js');
_kms('//scripts.kissmetrics.com/' + _kmk + '.2.js');
</script>

cf.: https://app.kissmetrics.com/setup/integration/9ac2445636036f9151b84b444b1ae78d105d0f7a

This is really fancy and I want to know why I can't do it more simply than this.

Opening the file i.kissmetrics.com/i.js we see the one-liner:

if(typeof(_kmil) == 'function')_kmil();

which means 'run _kmil() if you recognize _kmil as a function.' Meanwhile, _kmil() is an alias of KM.ikmq(), a function defined in the second script that you see.

It seems that the trouble appears when that second script, scripts.kissmetrics.com/61d817358af517ab2975dbb768eeb1d6d0d07c4b.2.js° either fails to load or has a delay in loading.

I want to do the following instead: Put scripts.kissmetrics... into the head node of my html, and then, rather than include i.js, simply run the function window.KM.ikmq() just before I register my listeners for KISSMetrics-tracked click events.

What would be the drawbacks of this, if any?

Totally optional bonus question: what is the purpose of the first line of code in the snippet above var _kmq = _kmq || []; if the variable _kmq is not used in the remainder of the script?

° the hexadecimal string is a fake key used here for demonstration purposes

pgblu
  • 662
  • 1
  • 7
  • 29
  • I'm having an issue with their scripts not loading on my site. Were you able to get it working as you've outlined it? My js-fu is not up to the task. TIA. – bryanus Apr 22 '16 at 17:58
  • 1
    A quick fix I did was to host the JS file myself. My site is using static s3 webste hosting through Cloudfront, and I think it was loading too fast for the KM script (i.js) file to load. So hosting it myself, it is not failing anymore. Also, their current script uses a CNAME for the second script (scripts.kissmetrics.com), but my earlier script uses a Cloudfront URL (//doug1izaerwt3.cloudfront.net). When I updated my script to use the CNAME, it failed, but using my original CF URL it loads fine. Maybe changing yours to the CF URL will help, too. – bryanus Apr 22 '16 at 18:07
  • It's not that it doesn't work, it has always worked fine, I just didn't understand the need for an additional one-liner script. – pgblu Apr 22 '16 at 19:38

0 Answers0