Wait for Facebook Pixel Load

user2297550 picture user2297550 · Jan 20, 2017 · Viewed 12.1k times · Source

I want to detect in my JavaScript code that the load of a Facebook pixel has been completed. Is this possible?

For reference here is the Facebook Pixel Tracking code:

<script>
!function(f,b,e,v,n,t,s){if(f.fbq)return;n=f.fbq=function(){n.callMethod?
n.callMethod.apply(n,arguments):n.queue.push(arguments)};if(!f._fbq)f._fbq=n;
n.push=n;n.loaded=!0;n.version='2.0';n.queue=[];t=b.createElement(e);t.async=!0;
t.src=v;s=b.getElementsByTagName(e)[0];s.parentNode.insertBefore(t,s)}(window,
document,'script','//connect.facebook.net/en_US/fbevents.js');
// Insert Your Facebook Pixel ID below. 
fbq('init', 'FB_PIXEL_ID');
fbq('track', 'PageView');
</script>
<!-- Insert Your Facebook Pixel ID below. --> 
<noscript><img height="1" width="1" style="display:none"
src="https://www.facebook.com/tr?id=FB_PIXEL_ID&amp;ev=PageView&amp;noscript=1"
/></noscript>

Breaking it down, it seems that fbq('init', ...) causes a script tag to be added with the async attribute set and src set to //connect.facebook.net/en_US/fbevents.js.

Subsequently the call to fbq('track', ...) somehow causes an HTTP GET to an image via one redirect.

How to detect that all the steps are complete, especially that the final image load is complete?

Answer

Kelly Selden picture Kelly Selden · Jun 30, 2017

I took a stab at this. Given a callback function named myCallback and your private id named myId, use this code:

  (function wait() {
    // check for the generic script
    // easiest check to prevent race condition
    if (fbq.version > '2.0') {
      // now check for the custom script
      // `fbq.on` is now ready (`fbq.once` would be better but has a bug)
     fbq.on('configLoaded', function (name) {
        if (name === myId) {
          myCallback();
        }
      });
    } else {
      setTimeout(wait, 10);
    }
  })();

myCallback will be called once everything is ready. This is accurate as of fbq.version="2.7.17";

Reference https://github.com/poteto/ember-metrics/pull/151