Home > Back-end >  Display partial dynamic content once it is built and appended to the page
Display partial dynamic content once it is built and appended to the page

Time:02-03

I am supporting a website. On one of the pages, the site uses ajax to retrieve data from the backend and, after receiving data, build charts (i.e. pie and bar charts) one by one and append each chart to the page. The 3rd party chart tool is Highcharts. Here is the code structure:

HTML:

<div id="charts"></div>

Javascript:

$.ajax({
    url: backend_URL
    dataType: json,
    success: function(data) {
      var container = $('#charts');
      $.each(data, function(index, item) {
         var chart = ...build-a-chart-by-using-data-item-and-Highcharts...;
         container.append(chart);
      }
    }
});

The problem with this code is that the page doesn't display anything until all charts are built and appended. If there are 100 charts, then it is a quite long wait for a user. The better user experience should be building a chart and showing it to the user so that the user can see the progress and look at what is displayed (instead of seeing a blank screen or a modal spinning wheel). How can I do it the better way? I must be missing something.

CodePudding user response:

In your query, you create one container and load data into it, which is possibly why it doesn't work smoothly.

You are loading large amounts of data at once. Instead, you could try creating separate divs for each chart.

Demo: http://jsfiddle.net/BlackLabel/59ucxq1a/

Highcharts.ajax({
  url: 'https://cdn.jsdelivr.net/gh/highcharts/[email protected]/samples/data/activity.json',
  dataType: 'text',
  success: function(data) {

    data = JSON.parse(data);
    data.datasets.forEach(function(dataset, i) {

        var chartDiv = document.createElement('div');
      chartDiv.className = 'chart';
      document.getElementById('container').appendChild(chartDiv);

      Highcharts.chart(chartDiv, {
        title: {
          text: dataset.name,
        },
        series: [{
          data: dataset.data,
          name: dataset.name,
          type: dataset.type,
        }]
      });
    });
  }
});
.chart {
    height: 220px;
}
<script src="https://code.highcharts.com/highcharts.js"></script>
<script src="https://code.highcharts.com/modules/data.js"></script>
<script src="https://code.highcharts.com/modules/accessibility.js"></script>

<div id="container"></div>

  • Related