最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Check if Mixpanel library has been loaded - Stack Overflow

programmeradmin6浏览0评论

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')

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')
Share Improve this question edited Mar 1, 2023 at 7:16 Syed M. Sannan 1,3634 gold badges13 silver badges33 bronze badges asked Aug 25, 2015 at 11:58 Dmytro PastovenskyiDmytro Pastovenskyi 5,4396 gold badges40 silver badges58 bronze badges
Add a ment  | 

4 Answers 4

Reset to default 2

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')

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 _mixpanelplete = setInterval(function(){
    if(mixpanel.hasOwnProperty('get_distinct_id'))
    {
        clearInterval(_mixpanelplete);
        //init your stuff here
    }
},100);

Here is my remendation 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);
    }
}

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])
发布评论

评论列表(0)

  1. 暂无评论