Skip to content

Instantly share code, notes, and snippets.

@sperand-io
Last active October 31, 2023 10:05
Show Gist options
  • Save sperand-io/4725e248a35d5005d68d810d8a8f7b29 to your computer and use it in GitHub Desktop.
Save sperand-io/4725e248a35d5005d68d810d8a8f7b29 to your computer and use it in GitHub Desktop.
Example of using analytics.js conditional loading with TrustArc Consent Manager
const [isConsentRequired, destinations] = await Promise.all([
shouldRequireConsent(),
fetchDestinations([writeKey, ...otherWriteKeys])
])
const newDestinations = getNewDestinations(
destinations,
destinationPreferences
)
conditionallyLoadAnalytics({
writeKey,
destinations,
destinationPreferences,
isConsentRequired
})
export default function conditionallyLoadAnalytics({
writeKey,
destinations,
destinationPreferences,
isConsentRequired,
shouldReload = true
}) {
const integrations = {All: false, 'Segment.io': true}
let isAnythingEnabled = false
if (!destinationPreferences) {
if (isConsentRequired) {
return
}
// Load a.js normally when consent isn't required and there's no preferences
if (!window.analytics.initialized) {
window.analytics.load(writeKey)
}
return
}
for (const destination of destinations) {
const isEnabled = Boolean(destinationPreferences[destination.id])
if (isEnabled) {
isAnythingEnabled = true
}
integrations[destination.id] = isEnabled
}
// Reload the page if the trackers have already been initialised so that
// the user's new preferences can take affect
if (window.analytics.initialized) {
if (shouldReload) {
window.location.reload()
}
return
}
// Don't load a.js at all if nothing has been enabled
if (isAnythingEnabled) {
window.analytics.load(writeKey, {integrations})
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment