googleanalytics / autotrack

Automatic and enhanced Google Analytics tracking for common user interactions on the web.
Other
4.92k stars 564 forks source link

Auto start impression #116

Open cemo opened 7 years ago

cemo commented 7 years ago

The current way to start of impression

ga('require', 'impressionTracker', {
  elements: ['foo', 'bar']
});

It would be cool to start automatically these elements based on some data attributes such as data-impression-element. These elements can be searched when dom is ready.

philipwalton commented 7 years ago

That's an interesting idea. I'll have to think about how/whether that could work.

Note that you can kind of do this today with something like the following:

ga('require', 'impressionTracker');

document.addEventListener('DOMContentLoaded', () => {
  var elementsWithDataAttributes = Array.from(
      document.querySelectorAll('[data-impression-element]'))
          .map((el) => el.getAttribute('data-impression-element'));

  ga('impressionTracker:observeElements', elementsWithDataAttributes);
});