Using Google Optimize in a plugin initializer JS

Hey everyone, i have a problem when i enable v4_gtag for analytics instead of v3_analytics, i need GTag for Google Optimize but i keep getting an error that gtag is not a function.

i am calling the gtag function inside a plugin js file, can someone provide more context on why this isn’t working ?

here is a sample of how i’ve written the code, Thank you in advance

export default {
  name: 'common-init',
  after: 'inject-objects',
  initialize() {
    gtag('event', 'optimize.callback', {
      name: settings.optimize_js_experiment_id,
      callback: (variation) => {
       console.log(`Variation: ${variation}`)
      }
    })
  }
}

Where your gtag function define?

i would assume its defined as part of Discourse when. i enable gtag from settings

You will still need to import even it define at somewhere already.

so i still need to add the GTag importing script manually somewhere ?

Seems gtag is define at runtime under window object, so you don’t have to import it again but call it in runtime like window.gtag.

i was able to define the function on startup and i think discourse is gonna redefine it when it loads which is currently working ok, but i have another problem now, when i add my ga tracking code in ga universal tracking code it still includes analytics.js even though i am using v4_gtag, is this an expected behavior ? won’t. that make an issue of sending duplicate events ?