[Chartjs]-ChartJS in Datatable cell performance

1๐Ÿ‘

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();

});

0๐Ÿ‘

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

Leave a comment