Iggy codes

The Click Science

March 14, 2019

TLDR;

Analytics implementation from scratch is good, when you have to rework every bit it sucks. How can we fix it?

I have been working and thinking for a while about how people implement analytics.

Very often, the customer behaviour team, sometimes called the ‘Optimisation team’, (I like to call them the click team), ask us (frontends devs) to write them some piece of code to track events being fire and send some data to the window object.

Sometimes is easy and sometimes is like the pyramide of doom, callback hell and stuff. If you are lucky enough and you have to write everything from scratc. Wohoo! Happy days for you ahead as nothing has been done!

HOWEVER, if you have to refactor or rework all the analytics from some already build markup then good luck with that.

I believe there must be a better way. Of course CMSs implements alt attributes but I know more than one author that doesnt care enough to fill them. What if we could reuse part of the DOM elements already built?

Let’s think about it…

<a href='https://iggy.codes'>my awesome website</a>

So if we want to track a click event for this link we will have to use the following:

document.querySelectorAll('a').forEach(node => node.addEventListener('click', e=>{console.log('event captured'); //push to analytics}));

How do we get the text and remaining attributes that we need to push to the datalayer? What if instead of click event we want to track a hover event on that anchor?

Maybe we could do something like this.

<a href='https://iggy.codes' class='dl' alt='Link to ' data-dl-events='click, hover' data-dl-text='Awesome Code'>my awesome website</a>

Here we can use the power of the document.querySelector all, and scan our code based to find items tagged with the class dl. (By the way, dl means datalayer, but you can rename to whatever you want.) Once you detect that class, you can extract the dataset attributes on the node, and populate you datalayer object before pushing it to the analytics system.

If we keep this consistent, then we can automate a node script to automatically regenerate the analytics codes and include that into our build.

That is why i am creating picoDL, a small and lighweight lib/module/script to help to do this task and don’t pollute the codebase with unecessary stuff. Furthermore, it will reduce the time for setting up analytics, reducing the time spent by the click team to get started and track those awesome click links.

Funnily enough, I haven’t analytics here (Trololo!) but I do really believe we could improve the way we deal with these situations. We should work smarter, not harder.


Iggy Pops - Ignacio Garcia Villanueva

Written by Iggy Pops - Ignacio Garcia Villanueva , a javascript journeyman rocking his way to the top of the JS world. You should follow him on Twitter... he is good!