簡體   English   中英

檢查是否已加載Mixpanel庫

[英]Check if Mixpanel library has been loaded

我們的網站正在使用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')

正確的方法是使用初始化屬性,該屬性將在加載庫后觸發。 有關更多信息,請閱讀如何防止get_distinct_id和get_property返回未定義

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

這是我對那些嘗試運行依賴於混合面板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);
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM