Dmytro Pastovenskyi
Dmytro Pastovenskyi

Reputation: 5419

Check if Mixpanel library has been loaded

Our website is using mixpanel for tracking.

var mixPanelId = mixpanel.get_distinct_id();
$('#trial, #order').each(function () {
  $(this).append("<input type='hidden' value='"+mixPanelId+"' name='MixpanelId' />");
});

However in case mixpanel is not loaded, the main object does not have get_distinct_id. What would be the most correct way to handle this situation?

So far I'm doing a normal js property check (but I'm wondering if Mixpanel has a more correct way to do it):

mixpanel.hasOwnProperty('get_distinct_id')

Upvotes: 5

Views: 7001

Answers (4)

Dmytro Pastovenskyi
Dmytro Pastovenskyi

Reputation: 5419

The right way is to use the init property that will be triggered once the library is loaded. For more information read How to prevent get_distinct_id & get_property from returning undefined

mixpanel.init('token-id', {'loaded':function() {
    var distinct_id = mixpanel.get_distinct_id();
}})

Checking for the property is not really the correct way to handle a situation. You may do this check before the library is loaded.

mixpanel.hasOwnProperty('get_distinct_id')

Upvotes: 2

JorgeeFG
JorgeeFG

Reputation: 5981

Just wanted to share my solution

const sleep = (ms: number) => {
  return new Promise(resolve => setTimeout(resolve, ms));
}

const waitForMixpanel = () => {
  return new Promise(async (resolve, reject) => {
    const maxRetries = 15;

    for (let i = 0; i < maxRetries; i++) {
      if (typeof window.mixpanel !== 'undefined' && window.mixpanel.__loaded) {
        return resolve(true);
      }

      await sleep(500);
    }

    return reject(false);
  })
}

Then you can use it like this, in React for example.

useEffect(() => {
    if (consents.functionality) {

    }
    if (consents.performance) {
      waitForMixpanel()
        .then(() => {
          optInMixpanel()
        })
        .catch(_ => {
          console.log('Timed Out Waiting for Mixpanel')
        })
    }
    if (consents.targeting) {

    }
  }, [consents])

Upvotes: 0

zeusstl
zeusstl

Reputation: 1865

Here is my recommendation for those trying to run code dependent on the mixpanel distinct_id:

function method1( var1, counter ) {
    if ( typeof counter == "undefined" || counter == null )
        var counter = 0;
    try {
        var mixpanel_distinct_id = mixpanel.get_distinct_id();
        // Code that is dependent on distinct_id goes here
    } catch(e) {
        var max_attempts = 40; // How long do you want it to try before letting it fail
        counter++;
        if ( counter < max_attempts )
            setTimeout( function(){ method1(var1, counter) }, 50);
    }
}

Upvotes: 0

Roboroads
Roboroads

Reputation: 1709

I don't know if mixpanel has an onload (or so) callback (havn't seen one in the reference), so what you could do is intervalling to check if the variable is set.

Caution: It's a bit dirty to use.

var _mixpanelcomplete = setInterval(function(){
    if(mixpanel.hasOwnProperty('get_distinct_id'))
    {
        clearInterval(_mixpanelcomplete);
        //init your stuff here
    }
},100);

Upvotes: 1

Related Questions