Facebook Pixel + Google Tag Manager + fbq events

Alexander G picture Alexander G · Oct 27, 2017 · Viewed 13k times · Source

I'm using Google Tag Manager to deliver Facebook Pixel.

Then, I fire events using code like this

  <body>
...
        <script>
            fbq('track', 'ViewContent', { 
                content_type: 'product',
                content_ids: ['1234'],
                content_name: 'ABC Leather Sandal',
                content_category: 'Shoes',
                value: 0.50,
                currency: 'USD'
            });
        </script>
    </body>

But when the code is executed I got an error since Facebook Pixel is loaded asynchronously and fbq is not available yet.

Uncaught ReferenceError: fbq is not defined

What should I do?

Answer

vir us picture vir us · Jul 5, 2019

Couldn't get Eike's approach to work and ended up with the below "dirty workaround" (basically it just waits till the fbq is inited):

<script>
    function waitForFbq(callback){
        if(typeof fbq !== 'undefined'){
            callback()
        } else {
            setTimeout(function () {
                waitForFbq(callback)
            }, 100)
        }
    }

    waitForFbq(function () {
        fbq('track', 'Registered');
    })
</script>

Maybe it will help someone as well