1

How to add ad-hoc pixels with Segment

Segment currently supports several web pixels, but unfortunately not yet all of them (if you want them on our platform, direct them to this page). However, it is still possible to add ad-hoc pixels to your site when certain events fire. Here is a guide to help you do that!

One solution would be to enable Google Tag Manager via Segment and use their container to fire pixels. You can learn more about doing this in GTM here.

Alternatively, if you don't mind configuring these in code, you can use analytics.js's emitter features and some small utility functions to elegantly do this on your own:

// browsers download the image immediately upon construction, so no need to do any dom insertion
function loadImage(attrs, fn) {
  fn = fn || function(){};
  var img = new Image;
  img.onload = function(){ fn(); };
  img.src = attrs.src;
  img.width = 1;
  img.height = 1;
  return img;
}

// defining this so that we can easily create the pixel's URL/path/query-string
function fmt(str){
  var args = [].slice.call(arguments, 1);
  var j = 0;

  return str.replace(/%([a-z])/gi, function(_, f){
    return fmt[f]
      ? fmt[f](args[j++])
      : _ + f;
  });
}

// %s for strings, %d for numbers!

fmt.s = String;
fmt.d = parseInt;

analytics.on('track', function(event, props){
  // whatever control flow makes sense for your needs will work here!
  switch (event) {
    case 'Conversion Event':
      loadImage({ src: fmt('//1pixel.com/%s/stuff?id=%s&revenue=%d', event, props.event_id, props.revenue) });
      loadImage({ src: fmt('//2pixel.com/%s/stuff?id=%s&revenue=%d', event, props.event_id, props.revenue) });
      break;
    case 'Other Conversion Event':
      loadImage({ src: fmt('//1pixel.com/%s/stuff?id=%s&revenue=%d', event, props.event_id, props.revenue) });
      loadImage({ src: fmt('//2pixel.com/%s/stuff?id=%s&revenue=%d', event, props.event_id, props.revenue) });
      break;
  }
});

Check out the output when the above code is executed in the console:

However, we're absolutely considering adding this feature to our roadmap right now (user-defined ad-hoc pixel integrations).

1reply Oldest first
  • Oldest first
  • Newest first
  • Active threads
  • Popular