Igor's lucky notes
Note written on May 13, 2024

Facebook lib to handle facebook pixel production-ready

We did! As I said in my previous note, I found a new lib to handle Facebook pixel.

I discussed the lib design extensively with Tanuki and sent this PR.

I learned from him which don't matter if fb script loads after the call init event because it is shipped with a queue system to handle that behavior.

But how? Here is the script provided by Facebook beautified

export function addScript(f: Window, b: Document, e: string, v: string, n?: any, t?: HTMLScriptElement, s?: HTMLScriptElement): FacebookQuery {
  if (f.fbq) { return f.fbq }

  n = f.fbq = function() {
    if (n.callMethod) {
      // eslint-disable-next-line prefer-spread, prefer-rest-params
      n.callMethod.apply(n, arguments)
    } else {
      // eslint-disable-next-line prefer-rest-params
      n.queue.push(arguments)
    }
  }

  if (!f._fbq) { f._fbq = n }

  n.push = n
  n.loaded = true
  n.version = '2.0'
  n.queue = []

  t = b.createElement(e) as HTMLScriptElement
  t.async = true
  t.src = v

  s = b.getElementsByTagName(e)[0] as HTMLScriptElement
  s.parentNode!.insertBefore(t, s)

  return n
}

What is mandatory is to call that first script as soon as possible and it will instantly make window.fbq available through n = f.fbq = function () {} and we will instantly be able to call fbq('init'). Our calls will be stored in n.queue until the fbevents.js is loaded. When it is, it will process the queue and send the events to Facebook

Here are the docs to use with Nuxt.