我怎么知道是否加载了Google Visualization

J.A*_*.L. 9 javascript google-visualization

我在一些网页上显示谷歌的图表.但我无法保证我的客户可以通过网络访问Google:客户端计算机将与我的网络服务器(可以访问Google)位于同一个局域网中,但我不保证所有客户端都可以访问局域网以外的地址.

我想使用Google Charts向可以访问它的客户端显示数据,并向那些不能访问它的人显示纯HTML表格.

我尝试将变量设置为false,并在加载Google Visualization API时调用的方法中将其更改为true:

var canAccessGoogleVisualizationVar = false;
google.load('visualization', '1', {packages: ['corechart'], callback: canAccessGoogleVisualization});
function canAccessGoogleVisualization() 
{
    canAccessGoogleVisualizationVar = true;
}
Run Code Online (Sandbox Code Playgroud)

但它似乎没有用.

如何从客户端了解Google Visualization是否可访问?


更新:上面的代码不起作用,因为下面的代码(我之前没有发布,因为我认为没有意义):

google.setOnLoadCallback(drawVisualization);

function drawVisualization() 
{
    // Check if Google Visualization is loaded
    if (!canAccessGoogleVisualizationVar) {
        alert('Can't access Google Visualization');
    }

    // The following code can be any of the samples from Google (see http://code.google.com/apis/ajax/playground/?type=visualization#pie_chart).
    var data = new google.visualization.DataTable();
    // Add columns and values to data
    ...
    // Call new google.visualization.AnyChartBuilderFromTheAPI(<element>).draw(data);
}
Run Code Online (Sandbox Code Playgroud)

我发现我的代码没有工作,因为,如果canAccessGoogleVisualizationVar == true,在if不转移,如果其false时,function drawVisualization()就不会被执行.

所以我在函数外面进行了if-test:

google.setOnLoadCallback(drawVisualization);

function drawVisualization() 
{
    // Any drawVisualization unchanged from the samples from Google (see http://code.google.com/apis/ajax/playground/?type=visualization#pie_chart).
}

// Check if Google Visualization is loaded at the end of this <script> </script>
if (!canAccessGoogleVisualizationVar) {
    alert('Can't access Google Visualization');
}
</script>
Run Code Online (Sandbox Code Playgroud)

但现在它不起作用,因为评估if (!canAccessGoogleVisualizationVar)是在线调用方法之前执行google.load(?, ?, canAccessGoogleVisualization);canAccessGoogleVisualization().

我怎么能确定我在尝试执行调用canAccessGoogleVisualizationVar 读取的值google.load(...);

Dav*_*idW 12

你可以试试

function canAccessGoogleVisualization() 
{
    if ((typeof google === 'undefined') || (typeof google.visualization === 'undefined')) {
       return false;
    }
    else{
     return true;
   }
}
Run Code Online (Sandbox Code Playgroud)