Google 绘制图表的可视化在外部 Java 脚本文件中不起作用

Google Visualization for drawing charts is not working in external Java Script File

这是我的 html 代码。它包含一个 div 和一个外部 javascript 文件。如果我将这个外部 js 文件用作内部文件,它会根据数据完美地绘制饼图,但是当我将它用作外部 js 文件时,它什么也没有显示。

代码 .html

<html>
<head>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript" src="externalscript.js"> </script>
</head> <body>
<div id="piechart" style="width: 900px; height: 500px;"></div>
</body></html>

externalscript.js

    google.load("visualization", "1", {packages:["corechart"]});
    var dataArray =[['Task', 'Hours per Day']];
    var arr1=['Work','Eat','Commute','Watch TV','Sleep'];
    var arr2=[11,2,2,2,7]; (var n=0; n < arr2.length; n++) { 
    dataArray.push([arr1[n], parseInt(arr2[n])]);
    }
    var data = new google.visualization.arrayToDataTable(dataArray);
    var options = {
      title: 'My Daily Activities'
    };
    var chart = new google.visualization.PieChart(document.getElementById('piechart'));
    chart.draw(data, options);

你需要这个。

google.setOnLoadCallback(drawData);

 google.load("visualization", "1", {packages:["corechart"]});
 function drawData(){
    var dataArray =[['Task', 'Hours per Day']];
    var arr1=['Work','Eat','Commute','Watch TV','Sleep'];
    var arr2=[11,2,2,2,7]; 
    for(var n=0; n < arr2.length; n++) { 
    dataArray.push([arr1[n], parseInt(arr2[n])]);
    }
    var data = new google.visualization.arrayToDataTable(dataArray);
    var options = {
      title: 'My Daily Activities'
    };
    var chart = new google.visualization.PieChart(document.getElementById('piechart'));
    chart.draw(data, options);
}
google.setOnLoadCallback(drawData);
<html>
<head>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
</head> <body>
<div id="piechart" style="width: 900px; height: 500px;"></div>
</body></html>