The code I have now is currently working, but I'm looking for ways to optimize it, and really, to just get any feedback.
I'm implementing this code through Ensighten (a tag management platform) as a custom javascript tag. Ensighten works by injecting tags either sync or async scripts on to a page. I've set this tag to fire after the DOM is ready.
What it does is creates a namespace, and then sets a function in that namespace to main (see main.js). The main function takes one argument, an object (see lookupTable.js), in which it takes that object, loops through the object, and if the object contains the correct key, it sets that key's value equal to campaignCode.
Next, the function looks to see if the campaignCode is not falsey, it then looks at the path (window.location.path) to see if it's either a courses
or a topics
page. If it's a topics
page it fires the analytics code. If it's a courses
page, it listens for a message from an iframe that a video was clicked. If the message from that iframe equals play button clicked
then it fires the other analytics code.
The main
function is called from the the lookupTable.js. Like so:
window.analytics.campaign.main(window.analytics.campaign.lookupTable);
Questions:
- Should I be checking if the main function's argument is an object?
- Is there a way I wouldn't have to check if the campaignCode is falsy? Could I check it in the if statement of the for loop?
- Am I declaring the analyticsTrack function in the correct way?
main.js
/*jslint browser:true*/
/*globals Bootstrapper*/
window.analytics = window.analytics || {};
window.analytics.campaign = window.analytics.campaign || {};
window.analytics.campaign.main = function (lookupTable) {
var path = window.location.pathname,
campaignCode = '',
prop;
function analyticsTrack (id) {
return Bootstrapper.insertScript('//www.example.com/click/services/Tracking/Click.ashx?CR_EAC=' + id);
}
for (prop in lookupTable) {
if (lookupTable.hasOwnProperty(prop) && path === prop) {
campaignCode = lookupTable[prop];
}
}
// check campaignCode
if (campaignCode) {
// if it's a topic page, fire a RIO tag onload
if (path.indexOf('topics') > -1) {
analyticsTrack(campaignCode);
}
// if it's a courses page
if (path.indexOf('courses') > -1) {
// listen for a message from the iframe
$(window).on('message', function (e) {
// check the message from the iframe, fire a RIO tag
if (e.originalEvent.data === 'play button clicked') {
analyticsTrack(campaignCode);
}
});
}
}
};
lookupTable.js
window.analytics = window.analytics || {};
window.analytics.campaign = window.analytics.campaign || {};
var campaign = window.analytics.campaign;
campaign.lookupTable = {
'/topics/123456': '300257956',
'/courses/234567': '300257957',
'/courses/34567': '300257958',
'/courses/15677789': '300257959',
'/topics/123457': '300257970'
};
campaign.main(campaign.lookupTable);