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