检查Mixpanel库是否已加载

Check if Mixpanel library has been loaded

本文关键字:加载 是否 Mixpanel 检查      更新时间:2023-09-26

我们的网站正在使用mixpanel进行跟踪。

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

然而,如果mixpanel没有加载,主对象没有get_distinct_id。处理这种情况最正确的方法是什么?

到目前为止,我正在做一个正常的js属性检查(但我想知道如果Mixpanel有一个更正确的方法来做到这一点):

mixpanel.hasOwnProperty('get_distinct_id')

正确的方法是使用init属性,该属性将在加载库时触发。有关更多信息,请参阅如何防止get_distinct_id &Get_property from return undefined

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

检查属性并不是处理这种情况的正确方法。您可以在加载库之前进行此检查。

mixpanel.hasOwnProperty('get_distinct_id')

我不知道mixpanel是否有一个onload(或左右)回调(在参考中没有看到一个),所以你可以做的是间隔检查变量是否设置。

注意:使用起来有点脏。

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

对于那些试图运行依赖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);
    }
}

只是想分享我的解决方案

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);
  })
}

那么你可以这样使用它,例如在React中。

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