简体   繁体   中英

Google charts not showing at first request, but on second only

I'm using Google charts to visualise company performance data. My Javascript looks as follows:

<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">

    google.load("visualization", "1", {packages:["corechart","line","geochart"], "callback": drawAllCompanyCharts});

    function drawAllCompanyCharts() {
        drawChart();
        drawLineChart();
        drawDonutChart();
        drawStackedChart();
        drawMarkersMap();
        drawChart();
    }
</script>

When a user clicks the button to show the charts page, nothing is shown and a

Uncaught ReferenceError: google is not defined

error appears. When clicking the button again, the charts appear as requierd, no errors.

I tried to use google.setOnLoadCallback(drawAllCompanyCharts); as shown here , but drawAllCompanyCharts() never gets called. Also putting it in a $(document).ready(function () { didn't make it work.

The error clearly indicates that the google object is not ready by the time I need it. So it's all about timing. How can I assure drawAllCompanyCharts() will only be called when the google object is ready? And why doesn't google.setOnLoadCallback(drawAllCompanyCharts); show any effect?

Any help is highly appreciated :-)

Try load your https://www.google.com/jsapi after your js code. This happened sometime that object not found if we load js earlier than code.

So try interchange there position.

<script type="text/javascript">

  google.load("visualization", "1", {packages:["corechart","line","geochart"], "callback": drawAllCompanyCharts});

  function drawAllCompanyCharts() {
      drawChart();
      drawLineChart();
      drawDonutChart();
      drawStackedChart();
      drawMarkersMap();
      drawChart();
  }
</script>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>

Or you can add timeout for request to google function.

<script type="text/javascript" src="https://www.google.com/jsapi"></script>

<script type="text/javascript">
setTimeout( function() {
  google.load("visualization", "1", {packages:["corechart","line","geochart"], "callback": drawAllCompanyCharts});

  function drawAllCompanyCharts() {
    drawChart();
    drawLineChart();
    drawDonutChart();
    drawStackedChart();
    drawMarkersMap();
    drawChart();
  }
}, 100);
</script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM