Skip to content

Instantly share code, notes, and snippets.

@joshed-io
Last active December 29, 2015 21:09
Show Gist options
  • Save joshed-io/7728341 to your computer and use it in GitHub Desktop.
Save joshed-io/7728341 to your computer and use it in GitHub Desktop.
Only add the Keen IO JS SDK to the page if it's not already there; otherwise configure a new client instance
// useful if you are injecting code into 3rd party websites that may already have Keen
// this code will use the Keen SDK on the page if found, or initialize it's own otherwise.
// this approach will work in the average case, but could break if the 3rd party website
// is modifying or configuring the Keen library in an unexpected way
// a more durable approach would be to use an iFrame containing only the SDK and pass it messages
var context = this;
var myKeenClient = null;
var projectId = "xxx";
var writeKey = "yyy";
function addKeenEvent(collection, properties) {
if (myKeenClient !== null) {
myKeenClient.uploadEvent(collection, properties);
} else {
if (typeof context.Keen === 'object') {
// put this logic inside the onChartsReady callback;
// The Keen.Client object isn't available until the full library is present
context.Keen.onChartsReady(function() {
myKeenClient = new context.Keen.Client({ projectId: projectId, writeKey: writeKey });
myKeenClient.uploadEvent(collection, properties);
});
} else {
context.Keen = {configure:function(e){this._cf=e},addEvent:function(e,t,n,i){this._eq=this._eq||[],this._eq.push([e,t,n,i])},setGlobalProperties:function(e){this._gp=e},onChartsReady:function(e){this._ocrq=this._ocrq||[],this._ocrq.push(e)}};(function(){var e=document.createElement("script");e.type="text/javascript",e.async=!0,e.src=("https:"==document.location.protocol?"https://":"http://")+"dc8na2hxrj29i.cloudfront.net/code/keen-2.1.0-min.js";var t=document.getElementsByTagName("script")[0];t.parentNode.insertBefore(e,t)})();
context.Keen.onChartsReady(function() {
myKeenClient = new context.Keen.Client({ projectId: projectId, writeKey: writeKey });
myKeenClient.uploadEvent(collection, properties);
});
}
}
}
addKeenEvent("foo", { "bar" : "baz "});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment