lundi 3 septembre 2018

Google charts draw becomes very slow in If clause

I have a Google column chart which is working just fine, although in some cases it could happen that the data set returned from the SalesQueryN.asp is empty. To avoid an error message being displayed, I tried to use an

if (condition) {} else {} 

clause to check if the data set is empty, otherwise it should draw the chart.

Without the if, the chart is drawn instantly, but this line

chart.draw(data, google.charts.Bar.convertOptions(options));

is within the else {} clause, the browser hangs for some 30 seconds. Eventually it does display part of the chart, but the performance is not acceptable, and it doesn't display the proper full chart.

Here is the Ajax code that I use to draw the chart.

    google.charts.setOnLoadCallback(function() { drawsdr(cYear,cMonth,'CST')});

    function drawsdr(rY, rM, rS) {
      if (rY === undefined) {
          rY = Date().getFullYear();
      }
      if (rM === undefined) {
          rM = Date().getMonth();
      }
      if (rS === undefined) {
          rS = 'CST';
      }
      $.ajax({
          url: "api/SalesQueryN.asp?P=T&Y=" + rY + "&M=" + rM + "&S=" + rS,
          dataType: "json",
          async: true,
          success: function (jsonData) {
             var data = new google.visualization.arrayToDataTable(jsonData);
             var chart = new google.charts.Bar(document.getElementById('s'+rS));
             var options = { 
                 title: rY + '-' + rM,
                 legend: { position: 'bottom' },
                 bar: { groupWidth: '80%' },
                 fontSize: xFS, fontName: xFo,
                 isStacked: false,
                 seriesType: 'bars',
                 vAxis: { format: '#,###' },
                 hAxis: { textStyle: { fontSize: xFS } }
             };
             if (data.getColumnLabel(0) == "empty") {
                document.getElementById("sCST").innerHTML = "<p>There is no data to display for " + rY + "-" + rM + "</p>";
             } else {
                chart.draw(data, google.charts.Bar.convertOptions(options));
             }
          },
          error: function (response) {
             alert(Object.keys(response));
             //alert(response.statusText);
             alert(response.responseText);
          }
        });
      }

I'm not quite sure why the if clause is affecting the performance so much.

My question now is how can I make the check on the data table without slowing down the chart's drawing?

Aucun commentaire:

Enregistrer un commentaire