philipwalton / analyticsjs-boilerplate

Examples and best practices for using analytics.js
ISC License
1.13k stars 59 forks source link

[Q]: ga maybe undefined because of async loading module #22

Open begoat opened 4 years ago

begoat commented 4 years ago

Firstly, thank you for this amazing library.

I have a question and hope get some suggestions.

Here is the question:

Code in boilerplate places tracking code in a separate file using code splitting tech via webpack. We can see the init function in analytics/base.js is executed after module get loaded.

init() {
  // Initialize the command queue in case analytics.js hasn't loaded yet.
  window.ga = window.ga || ((...args) => (ga.q = ga.q || []).push(args));
}

After async load module, other code(main logic of the website) is also executed. At the moment(init function in analytics/base.js hasn't been executed), if we trigger ga in window, it will be undefined.

Here is maybe a possible solution

Maybe we should mv window.ga=window.ga||function(){(ga.q=ga.q||[]).push(arguments)};ga.l=+new Date; to index.html ?