Implementing locking mechanism for SSR

In case you want to implement AB Tasty in a server-side rendering (SSR) environment, you might want to use our locking mechanism to prevent our tag from executing and modify the DOM before it fully loads, thus avoiding any reconciliation issues.

You will find here basic implementation examples for the three main JS frameworks and vanilla JS.

Next JS

_document.tsx
import { Html, Head, Main, NextScript } from 'next/document';

export default function Document() {
  return (
    <Html>
      <Head>
        {/* Lock AB Tasty before tag loads */}
        <script>{`window.lockABTastyTag = true;`}</script>
      </Head>
      <body>
        <Main />
        <NextScript />
      </body>
    </Html>
  );
}
_app.tsx
import { useEffect } from 'react';

function MyApp({ Component, pageProps }) {
  useEffect(() => {
    const tryUnlockABTasty = () => {
      if (typeof window?.unlockABTasty === 'function') {
        window.unlockABTasty();
      } else {
        setTimeout(tryUnlockABTasty, 100);
      }
    };
    tryUnlockABTasty();
  }, []);

  return <Component {...pageProps} />;
}

export default MyApp;

Angular

Index.html
<head>
  <script>
    window.lockABTastyTag = true;
  </script>
</head>
app.component.ts
import { AfterViewInit, Component } from '@angular/core';

@Component({
  selector: 'app-root',
  template: `<router-outlet></router-outlet>`
})
export class AppComponent implements AfterViewInit {
  ngAfterViewInit(): void {
    const tryUnlockABTasty = () => {
      if (typeof window.unlockABTasty === 'function') {
        window.unlockABTasty();
      } else {
        setTimeout(tryUnlockABTasty, 100);
      }
    };
    tryUnlockABTasty();
  }
}

VueJS

nuxt.config.js
export default {
  app: {
    head: {
      script: [
        { children: 'window.lockABTastyTag = true;' }
      ]
    }
  }
}
App.vue
export default {
  mounted() {
    if (typeof window !== 'undefined' && window.unlockABTasty) {
      window.unlockABTasty();
    }
  }
}

Vanilla JS

index.html
<head>
  <!-- Lock AB Tasty before the tag loads -->
  <script>
    window.lockABTastyTag = true;
  </script>

  <!-- AB Tasty tag here -->
  <script src="https://try.abtasty.com/.../abtasty.js" async></script>
</head>
script.js
window.addEventListener("DOMContentLoaded", function () {
  if (typeof window.unlockABTasty === "function") {
    window.unlockABTasty();
  }
});

Last updated

Was this helpful?