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

标签 javascript google-visualization

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

我想使用 Google Charts 向可以访问数据的客户显示数据,向不能访问数据的客户显示纯 HTML 表格。

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

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

但是好像不行。

我如何从客户端知道 Google 可视化是否可访问?


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

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

我注意到我的代码不起作用,因为如果 canAccessGoogleVisualizationVar == true,则 if 分支未被采用,如果它的 false函数 drawVisualization() 不会被执行。

所以我在函数外进行了 if 测试:

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>

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

在尝试执行对 google.load(...) 的调用之后,我如何确定正在读取 canAccessGoogleVisualizationVar 的值?

最佳答案

你可以试试

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

关于javascript - 我怎么知道是否加载了 Google Visualization,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9792023/

相关文章:

javascript - 谷歌甘特图不更新高度

javascript - 当我在饼图中选择一个切片时,我想显示切片选择的某种视觉表示

javascript - 带凉亭的 webpack 2

javascript - 如何以自定义模式切片数组?

javascript - 谷歌可视化 : Animated Line Graph --incremental rather than all at once?

javascript - 如何在选中复选框时显示条形图?

javascript - Google 图表分数数字

javascript - 不会打印出名字请帮忙

javascript - 如何在JS/jQuery中创建不同的交互模式?

javascript - Discord.js 13交互检查交互创建者是否在公会中