[TIP] Slim Events Tracking Library for Web Analysts
Back in time, I remember relying on jQuery for all the custom event tracking on my client websites, it was really great since it was covering the support for IE8
, IE9
. Since jQuery dropped the support for the older browser versions, the point of using it for the clicks / interactions tracking has lost most of the sense for me.
While jQuery is still a really good library it includes a ton of features that us the Web Analysts don't really need, since a 99% of the times we'll just be using the CSS selectors
engine from jQuery. Meaning that we are loading a lot of JS code that we won't be using. And you may be right that maybe the site is already using it and that it won't have any effect of the page loading, but with all the new tecnlogies, React
, Vue
, Angular
, SolidJS
, etc, the usage and insterest has been dropping a lot.
Latest jQuery version weights around 90KB, what about if I tell you that you could mostly replate it by a 300bytes-ish snippet that will cover most of your needs when talking about interactions tracking.
I've been using it for years in some clients without no major issues, it relies on the narive AddEventListener
from the browser and takes care of the Event Delegation . If you're coming from jQuery this equals to using the $.on
.
Here it goes the code:
var _slimedEventListener = function(element, event, selector, handler, target) {
element.addEventListener(event, function(evt) {
for (event = element,
target = evt.target; target != event; )
target.matches(selector) ? handler.call(event = target, evt, target) : target = target.parentNode
})
};
The usage would be like:
_slimedEventListener(document.body, 'mousedown', 'a', function(evt, matched) {
console.log("clicked element href", matched.getAttribute('href'))
console.log("clicked element data attributes", matched.dataset)
console.log("clicked element text", matched.innerText)
});
You can grab the current clicked element and it's data, you could use matched.parentNode
, matched.closest
, to get and navigate the parent elements or even using the
and matched
.querySelector
to find some other element withing the returned element.matched
.querySelectorAll
As you can see we replace the need of using an external 90KB library dependency, with a 300bytes snippet that will make use of the native browsers functionality. It may take some time to get used to how to grab some elements details ( innerText, dataset, href, getAttribute, hasClass ) instead of the jQuery funciontions names, but I really think that this will boost your code quality and make it more future proof ( sorry, to many clients dropping jQuery at their ends over the last years and breaking everything at my side : ) )
Hope this helps someone.