benjaminhoffman / gatsby-plugin-segment-js

Gatsby plugin for segment.com's analytic.js snippet
https://www.npmjs.com/package/gatsby-plugin-segment-js
MIT License
40 stars 28 forks source link

Can I write code to go in analytics.ready()? #22

Open shortcircuit3 opened 4 years ago

shortcircuit3 commented 4 years ago

I need to add google analytics auto linker for a multi domain site

shortcircuit3 commented 4 years ago

I got it to work but delayLoad needs to be set to false. I'd like to use delay load.

@Kilian Any idea how to achieve this? I can submit a PR.

Kilian commented 4 years ago

Not sure what you mean? Can you give a code example?

shortcircuit3 commented 4 years ago

This code works without the delay loader.

exports.onRenderBody = ({ setPostBodyComponents }) => {
  const attachCode = `
    window.analytics.ready(function () {
      // debugger;
      console.log('segment is ready', ga);

      // How to link domains
      ga('require', 'linker');
      ga('linker:autoLink', ['domain.com']);
    });
  `;

  setPostBodyComponents([
    <script
      key="1"
      dangerouslySetInnerHTML={{
        __html: attachCode,
      }}
    />,
  ]);
};

What if we added a ready callback option to the config?

 {
      resolve: `gatsby-plugin-segment-js`,
      options: {
        delayLoad: false,
        delayLoadTime: 1000,
+       onReady: () => { console.log('all integrations are ready') }
      },
}
shortcircuit3 commented 4 years ago

I tired to add the code but couldnt get it working. THoughts on how i should approach?

in plugin options

onReady: () => {
          console.log('ready')
        }
const {
    trackPage,
    prodKey,
    devKey,
    delayLoad,
    delayLoadTime,
+   onReady
  } = pluginOptions;

    window.segmentSnippetLoader = function (callback) {
        if (!window.segmentSnippetLoaded && !window.segmentSnippetLoading) {
          window.segmentSnippetLoading = true;

          function loader() {
            window.analytics.load('${writeKey}');
            window.segmentSnippetLoading = false;
            window.segmentSnippetLoaded = true;
+           window.analytics.ready(${onReady})
            if(callback) {callback()}
          };

          setTimeout(
            function () {
              "requestIdleCallback" in window
                ? requestIdleCallback(function () {loader()})
                : loader();
            },
            ${delayLoadTime} || 1000
          );
        }
      }
      window.addEventListener('scroll',function () {window.segmentSnippetLoader()}, { once: true });
    `;