Load airgap.js Asynchronously

To load airgap.js asynchronously, follow the steps below. Loading asynchronously ensures that airgap.js does not block load times. The tradeoff is that airgap.js can only regulate network traffic after it has loaded, so you are responsible for ensuring no trackers load before airgap.js.

Obtain your bundle ID from the Developer Settings page. The bundle ID will be in the format: https://transcend-cdn.com/cm/{bundle-id}/airgap.js.

Create a script element to load airgap.js asynchronously.

// Call `await getAirgap()` to load airgap.js

// Get your bundle ID at <https://app.transcend.io/consent-manager/developer-settings>
// Bundle ID is in this format: <https://transcend-cdn.com/cm/{bundle-id}/airgap.js>
const BUNDLE_ID = 'your-bundle-id-here';

let airgapAPI;
const getAirgap = () =>
  (airgapAPI ??= new Promise((resolve, reject) => {
    // Stub airgap.js ready queue
    if (!self?.airgap?.ready) {
      self.airgap = {
        readyQueue: [],
        ready(callback) {
          this.readyQueue.push(callback);
        },
        ...self?.airgap,
      };
    }

    // Wait for airgap.js to be ready
    self.airgap.ready((airgap) => {
      resolve(airgap);
    });

    const script = document.createElement('script');

    // Reject promise if airgap.js fails to load
    script.addEventListener('error', (evt) => {
      reject(evt);
    });

    // Specify load options:
    // e.g.
    // script.dataset.lazyLoadUi = 'on';
    // script.dataset.prompt = 'auto';
    // script.dataset.dismissedViewState = 'Closed';

    // Load airgap.js script asynchronously
    script.async = script.defer = true;
    script.src = `https://transcend-cdn.com/cm/${BUNDLE_ID}/airgap.js`;
    document.documentElement?.appendChild?.(script);
  }));

Beware: you are now importing airgap.js asynchronously. Since airgap.js can only regulate network traffic after it is loaded, you are now responsible for ensuring no trackers load before airgap.js!