Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Refactor commercial boot process #1764

Merged
merged 11 commits into from
Feb 3, 2025
5 changes: 5 additions & 0 deletions .changeset/famous-poems-count.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@guardian/commercial': minor
---

Refactor boot logic for readability
30 changes: 20 additions & 10 deletions src/commercial.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,16 @@
import type { ConsentState } from '@guardian/libs';
import { getConsentFor, onConsent } from '@guardian/libs';
import { commercialFeatures } from './lib/commercial-features';

const shouldBootConsentless = (consentState: ConsentState) => {
return (
window.guardian.config.switches.optOutAdvertising &&
consentState.tcfv2 &&
!getConsentFor('googletag', consentState) &&
!commercialFeatures.adFree
);
};

/**
* Choose whether to launch Googletag or Opt Out tag (ootag) based on consent state
*/
Expand All @@ -11,20 +21,20 @@ void (async () => {
// - in TCF region
// - no consent for Googletag
// - the user is not a subscriber
if (
window.guardian.config.switches.optOutAdvertising &&
consentState.tcfv2 &&
!getConsentFor('googletag', consentState) &&
!commercialFeatures.adFree
) {
if (shouldBootConsentless(consentState)) {
void import(
/* webpackChunkName: "consentless" */
'./init/consentless'
/* webpackChunkName: "consentless-advertising" */
'./init/consentless-advertising'
Comment on lines +26 to +27
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is very minor so feel free to ignore :) What do we gain anything by adding -advertising to all the chunks? Is it to help searching in dev tools?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It was only to make the distinction between code that loads an ad and the ad free code really explicit to anyone looking at it for the first time. I'm not set on it at all - happy to go with the majority opinion!

).then(({ bootConsentless }) => bootConsentless(consentState));
} else if (commercialFeatures.adFree) {
void import(
/* webpackChunkName: "ad-free" */
'./init/ad-free'
).then(({ bootCommercialWhenReady }) => bootCommercialWhenReady());
} else {
void import(
/* webpackChunkName: "consented" */
'./init/consented'
/* webpackChunkName: "consented-advertising" */
'./init/consented-advertising'
).then(({ bootCommercialWhenReady }) => bootCommercialWhenReady());
}
})();
29 changes: 29 additions & 0 deletions src/init/ad-free.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
import { bootCommercial } from '../lib/commercial-boot-utils';
import { adFreeSlotRemove } from './consented/ad-free-slot-remove';
import { init as initComscore } from './consented/comscore';
import { init as initIpsosMori } from './consented/ipsos-mori';
import { removeDisabledSlots as closeDisabledSlots } from './consented/remove-slots';
import { initTeadsCookieless } from './consented/teads-cookieless';
import { init as initTrackGpcSignal } from './consented/track-gpc-signal';
import { init as initTrackScrollDepth } from './consented/track-scroll-depth';

// modules not related to ad loading
const commercialModules = [
adFreeSlotRemove,
closeDisabledSlots,
initComscore,
initIpsosMori,
initTeadsCookieless,
initTrackScrollDepth,
initTrackGpcSignal,
];

const bootCommercialWhenReady = () => {
if (!!window.guardian.mustardCut || !!window.guardian.polyfilled) {
void bootCommercial(commercialModules);
} else {
window.guardian.queue.push(() => bootCommercial(commercialModules));
}
};

export { bootCommercialWhenReady };
56 changes: 56 additions & 0 deletions src/init/consented-advertising.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
import { init as prepareAdVerification } from '../lib/ad-verification/prepare-ad-verification';
import { bootCommercial } from '../lib/commercial-boot-utils';
import { adFreeSlotRemove } from './consented/ad-free-slot-remove';
import { init as initComscore } from './consented/comscore';
import { initDfpListeners } from './consented/dfp-listeners';
import { initDynamicAdSlots } from './consented/dynamic-ad-slots';
import { initFillSlotListener } from './consented/fill-slot-listener';
import { init as initIpsosMori } from './consented/ipsos-mori';
import { init as initMessenger } from './consented/messenger';
import { init as prepareA9 } from './consented/prepare-a9';
import { init as prepareGoogletag } from './consented/prepare-googletag';
import { initPermutive } from './consented/prepare-permutive';
import { init as preparePrebid } from './consented/prepare-prebid';
import { removeDisabledSlots as closeDisabledSlots } from './consented/remove-slots';
import { initTeadsCookieless } from './consented/teads-cookieless';
import { init as initThirdPartyTags } from './consented/third-party-tags';
import { init as initTrackGpcSignal } from './consented/track-gpc-signal';
import { init as initTrackScrollDepth } from './consented/track-scroll-depth';
import { reloadPageOnConsentChange } from './shared/reload-page-on-consent-change';
import { init as setAdTestCookie } from './shared/set-adtest-cookie';
import { init as setAdTestInLabelsCookie } from './shared/set-adtest-in-labels-cookie';

// all modules needed for commercial code and ads to run
const commercialModules = [
adFreeSlotRemove,
closeDisabledSlots,
initComscore,
initIpsosMori,
initTeadsCookieless,
initTrackScrollDepth,
initTrackGpcSignal,
initMessenger,
setAdTestCookie,
setAdTestInLabelsCookie,
reloadPageOnConsentChange,
preparePrebid,
initDfpListeners,
// Permutive init code must run before google tag enableServices()
// The permutive lib however is loaded async with the third party tags
() => initPermutive().then(prepareGoogletag),
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Maybe this could be part of a separate bit of work to tidy up the Permutive/Googletag code, but it would be nice if this could be a module unto itself like the others rather than a random hard-coded function and comment breaking up the array

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm going to address this in a separate PR, but yes, agreed!

initDynamicAdSlots,
prepareA9,
initFillSlotListener,
prepareAdVerification,
initThirdPartyTags,
];

const bootCommercialWhenReady = () => {
if (!!window.guardian.mustardCut || !!window.guardian.polyfilled) {
void bootCommercial(commercialModules);
} else {
window.guardian.queue.push(() => bootCommercial(commercialModules));
}
};

export { bootCommercialWhenReady };
163 changes: 0 additions & 163 deletions src/init/consented.ts

This file was deleted.

File renamed without changes.
59 changes: 59 additions & 0 deletions src/lib/commercial-boot-utils.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
import { log } from '@guardian/libs';
import { adSlotIdPrefix } from './dfp/dfp-env-globals';
import { reportError } from './error/report-error';
import { EventTimer } from './event-timer';

const tags: Record<string, string> = {
bundle: 'standalone',
};

const recordCommercialMetrics = () => {
const eventTimer = EventTimer.get();
eventTimer.mark('commercialBootEnd');
eventTimer.mark('commercialModulesLoaded');
// record the number of ad slots on the page
const adSlotsTotal = document.querySelectorAll(
`[id^="${adSlotIdPrefix}"]`,
).length;
eventTimer.setProperty('adSlotsTotal', adSlotsTotal);

// and the number of inline ad slots
const adSlotsInline = document.querySelectorAll(
`[id^="${adSlotIdPrefix}inline"]`,
).length;
eventTimer.setProperty('adSlotsInline', adSlotsInline);
};

const bootCommercial = async (
modules: Array<() => Promise<boolean | void>>,
): Promise<void> => {
log('commercial', '📦 standalone.commercial.ts', __webpack_public_path__);
if (process.env.COMMIT_SHA) {
log(
'commercial',
`@guardian/commercial commit https://github.com/guardian/commercial/blob/${process.env.COMMIT_SHA}`,
);
}

// Init Commercial event timers
EventTimer.init();
EventTimer.get().mark('commercialStart');
EventTimer.get().mark('commercialBootStart');

// Stub the command queue
// @ts-expect-error -- it’s a stub, not the whole Googletag object
window.googletag = {
cmd: [],
};

try {
return Promise.allSettled(modules.map((module) => module())).then(
recordCommercialMetrics,
);
} catch (error) {
// report async errors in bootCommercial to Sentry with the commercial feature tag
reportError(error, 'commercial', tags);
}
};

export { bootCommercial };
Loading