[Chartjs]-Jquery load with chart.js

2👍

Yes, if you are loading the HTML with the canvas element using jQuery .load(), you need to put the chart initialization in the complete callback, like so

$("#result").load("canvas.html", function () {
    var data = {
        labels: ['A', 'B', 'C', 'D', 'E', 'F', 'G'],
        datasets: [
            {
                data: [12, 23, 23, 43, 45, 12, 33]
            }
        ]
    };

    var ctx = document.getElementById("myChart").getContext("2d");
    var myLineChart = new Chart(ctx).Line(data);
});

where canvas.html is

<canvas id="myChart" height="300" width="500"></canvas>

The canvas element needs have a non-zero render size when the data is loaded, otherwise the chart won’t show up.

In most cases, putting the new Chart... in the right place (for e.g. in the callback, after a tab is visible, etc.) will be enough. When it’s not possible to identify such a point, using a setTimeout with enough delay to guarantee that the canvas element is rendered will work.

Leave a comment