Skip to content

Commit

Permalink
refactor: Add timeout and polling to call Segment/Cohesion Identify r…
Browse files Browse the repository at this point in the history
…eady
  • Loading branch information
julianajlk committed Nov 20, 2024
1 parent 10ff47b commit b15a43e
Showing 1 changed file with 63 additions and 37 deletions.
100 changes: 63 additions & 37 deletions public/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -42,49 +42,75 @@
multiparty: true,
}
})
</script>
<% } %>

try {
if (window.cohesion) {
window.cohesion("tagular:ready", function () {
window.analytics.ready(function () {
const cohesionAnonymId = window.tagular("getAliasSet")["anonymousId"];
const segmentAnonymId = window.analytics.user().anonymousId();
const segmentUserId = window.analytics.user().id();

// Segment Identify
window.analytics.identify(segmentUserId, {
cohesion_anonymous_id: cohesionAnonymId,
});
<script defer>
function waitForSegmentAnalyticsReady(callback, timeoutTime = 1000) { // 1 second
const intervalTime = 100; // 100 ms
let elapsedTime = 0;

// Tagular Identify
window.tagular("beam", {
"@type": "core.Identify.v1",
traits: {},
externalIds: [
{
id: segmentAnonymId,
type: "segment_anonymous_id",
collection: "users",
encoding: "none",
},
{
id: cohesionAnonymId,
type: "cohesion_anonymous_id",
collection: "users",
encoding: "none",
},
],
});
});
})
const interval = setInterval(() => {
if (window.analytics && typeof window.analytics.ready === 'function') {
clearInterval(interval);
callback();
} else {
console.log('Cohesion is not defined');
// Stop polling if Segment doesn't load in expected time interval
elapsedTime += intervalTime;
if (elapsedTime >= timeoutTime) {
clearInterval(interval);
console.log('Segment analytics did not load in the expected timeout')
}
}
} catch(e) {
console.log('Cohesion error: ', e);
}, intervalTime);
}

waitForSegmentAnalyticsReady(() => {
window.analytics.ready(() => {
console.log('Segment analytics is ready');
try {
if (window.cohesion) {
window.cohesion("tagular:ready", function () {
window.analytics.ready(function () {
const cohesionAnonymId = window.tagular("getAliasSet")["anonymousId"];
const segmentAnonymId = window.analytics.user().anonymousId();
const segmentUserId = window.analytics.user().id();

// Segment Identify
window.analytics.identify(segmentUserId, {
cohesion_anonymous_id: cohesionAnonymId,
});

// Tagular Identify
window.tagular("beam", {
"@type": "core.Identify.v1",
traits: {},
externalIds: [
{
id: segmentAnonymId,
type: "segment_anonymous_id",
collection: "users",
encoding: "none",
},
{
id: cohesionAnonymId,
type: "cohesion_anonymous_id",
collection: "users",
encoding: "none",
},
],
});
});
})
} else {
console.log('Cohesion is not defined');
}
} catch(e) {
console.log('Cohesion error: ', e);
}
})
}, 1000);
</script>
<% } %>
</head>
<body>
<div id="root">
Expand Down

0 comments on commit b15a43e

Please sign in to comment.