Skip to content

Commit

Permalink
refactor: Add interval polling for Segment/Cohesion Identify ready (#36)
Browse files Browse the repository at this point in the history
  • Loading branch information
julianajlk authored Nov 20, 2024
1 parent 10ff47b commit 6d02b3b
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 async>
function waitForSegmentAnalyticsReady(callback, timeoutTime = 4000) { // Default 4 sec, this is an async script
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);
}
})
}, 4000);
</script>
<% } %>
</head>
<body>
<div id="root">
Expand Down

0 comments on commit 6d02b3b

Please sign in to comment.