gatsby-plugin-segment-js icon indicating copy to clipboard operation
gatsby-plugin-segment-js copied to clipboard

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

Open shortcircuit3 opened this issue 6 years ago • 4 comments

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

shortcircuit3 avatar Dec 06 '19 13:12 shortcircuit3

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.

shortcircuit3 avatar Dec 06 '19 15:12 shortcircuit3

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

Kilian avatar Dec 06 '19 15:12 Kilian

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 avatar Dec 06 '19 15:12 shortcircuit3

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 });
    `;

shortcircuit3 avatar Dec 07 '19 19:12 shortcircuit3