plausible / plausible-tracker

Frontend library to interact with Plausible Analytics
https://github.com/plausible/plausible-tracker
MIT License
214 stars 46 forks source link

RFC: Make the library a singleton in the window context #49

Open ukutaht opened 1 year ago

ukutaht commented 1 year ago

There is a specific motivator for this RFC. When the enableAutoPageviews is called multiple times inadvertently by the library client, it registers multiple listeners on the pushState API and starts sending duplicate events.

It would be easy to avoid this mistake by storing some information on the window object and making any further calls to enableAutoPageviews act as a no-op.

Nice to have: in development mode, we should console.warn about using the library in an unintended way.

This begs two questions:

  1. Is there any concern with making the library act as a singleton? Put in other words, can registering multiple listeners for pushState and popState by this library ever be considered a feature not a bug?
  2. Is there some sort of common API to tell bundlers to elide some warnings or code in production mode as opposed to development mode? Can NODE_ENV be used for that?
sandstrom commented 1 year ago

Instead of making the library a singleton, I think effort should be put into something like this instead:

https://github.com/plausible/analytics/discussions/2414

That way, the library would be just that, a library (and a class), of which you could have many instances.

Then, the wrapper itself would act as a singleton, to make sure that it (by default) wouldn't setup multiple listeners.