Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/410.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 检查是否已加载Mixpanel库_Javascript_Mixpanel - Fatal编程技术网

Javascript 检查是否已加载Mixpanel库

Javascript 检查是否已加载Mixpanel库,javascript,mixpanel,Javascript,Mixpanel,我们的网站用于跟踪 var mixPanelId = mixpanel.get_distinct_id(); $('#trial, #order').each(function () { $(this).append("<input type='hidden' value='"+mixPanelId+"' name='MixpanelId' />"); }); 我不知道mixpanel是否有一个onload(大约)回调(在参考中没有看到),所以您可以做的是插入检查变量是否已设置

我们的网站用于跟踪

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

我不知道mixpanel是否有一个onload(大约)回调(在参考中没有看到),所以您可以做的是插入检查变量是否已设置

注意:使用起来有点脏

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

正确的方法是使用init属性,该属性将在加载库时触发。欲了解更多信息,请阅读

检查财产并不是处理情况的正确方法。您可以在加载库之前执行此检查

mixpanel.hasOwnProperty('get_distinct_id')

以下是我对那些试图运行依赖于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);
    }
}
函数方法1(变量1,计数器){
if(计数器类型==“未定义”| |计数器==null)
var计数器=0;
试一试{
var mixpanel_distinct_id=mixpanel.get_distinct_id();
//依赖于不同的\u id的代码位于此处
}捕获(e){
var max_attempts=40;//您希望它尝试多长时间才能失败
计数器++;
如果(计数器<最大尝试次数)
setTimeout(函数(){method1(var1,计数器)},50);
}
}

我只想提一下,实现已经更改,您需要执行
加载:(mixpanel)=>{const distinct_id=mixpanel.get_distinct_id()}
全局mixpanel在这个回调中不起作用,在发现之前打断了我的头
mixpanel.hasOwnProperty('get_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);
    }
}