javascriptmixpanel

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

Solution

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