Reputation: 137
So for some reason I have to put a tiny chart into a column cell. I did it with a simple div and initizialized every single chart:
<div>
<canvas id="6" height="50px" width="150px"></canvas>
</div>
Which works great for 10 dataset or 20. But i got a huge datatable with 380 rows and after "2 minutes" of waiting it even loads the charts for every single table row. Is there a better way to do it, or boost performance?
Upvotes: 2
Views: 2508
Reputation: 1541
Another option might be to use the drawCallback
option to use data in the table to render charts for the visible rows each time the DataTable is re-drawn for a page change.
Below is an simplified example of how this might be done for a doughnut chart.
$('#dataTableId').DataTable({
// I use the "columns" option to tell each column what data to show.
// One column should have a uniquely id'ed canvas.
"columns": [
{ "data": "id" },
{ "data": "A" },
{ "data": "B" },
{ "data": function(row){
return "<canvas height=\"40px\" width=\"40px\" id=\"chart"+row.id+"\"></canvas>";
},
"orderable": false}
],
"drawCallback": function() {
// Get data, only from the rows displayed on the current page.
var data = this.api().rows({page:'current'}).data();
// The first draw appears to have a length of 0,
// but subsequent ones have length equal to number of rows drawn.
if (data.length !== 0){
// Loop through each row to render each chart
for (var i = 0; i < data.length; i++) {
// Find the chart intended for this data
var ctx = $("#chart"+data[i].id);
// Make the chart
var newChart = new Chart(ctx, {
"type": "doughnut",
"data": {
"labels": [
"A",
"B"
],
"datasets": [{
"data": [data[i].A,data[i].B]
}],
},
}) // /Chart
}
}
}
// In a real table, the object passed into the DataTable() function will
// probably also use other options, such as "ajax", "serverSide" or
// "pageLength". For simplicity, only "columns" and "drawCallback" are
// shown in this example.
}); // /DataTable
Upvotes: 0
Reputation: 137
I found the solution. Like mentioned in this post: Pagination triggers I call a function which inits the visible charts on datatable draw. Means i only draw them when they get viewed. Nice performance and super slim solution.
$('#Table')
.on( 'draw.dt', function () { initSparkline(); } )
.dataTable();
});
Upvotes: 1