Loading javascript for chart.js

I have more than one charts made with charts.js on a single page:

For every chart I created a shortcode that starts like this (injected in the html generated by the page.md file) and if I have two shortcodes loading two charts on the page listed above, I call the same libraries twice:

<script src="/chart.js/Chart.bundle.js"></script>

<canvas id="EskomStatus" width="300" height="400"></canvas>

  var ctx = document.getElementById('EskomStatus');
  var myChart = new Chart(ctx, {
    type: 'pie',
    data: {
        labels: ['Buite Werking', 'Onderhoud', 'Cahora Bassa', 'Gasturbines', 'Krag Opgewek'],
        datasets: [{
        label: 'Kraglewering',
        data: [17,5,1,2,23],

My concern is that I am loading the Chart.bundle.js numerous times for every shortcode that looks like the above. Or maybe not? Or it could depend on the local browser? I simply don’t know.

I could modify the theme and load Chart.bundle.js in the section of the theme, but then it loads for those pages without charts.

What will the best practice be here?

Don’t worry

Don’t worry

some ideas here

This might be a simple solution: a Shortcode called in the content HTML before the other shortcodes requiring the Javascript. Thus the shortcode chartjs.html loads the appropriate chart.js libraries as well as supported libraries before the shortcodes invoking charts are inserted. This has the additional benefit that should I wish to change between the minified Javascript source vs the full source, or load additional libraries, this is done in one place for the whole site. And the javascript is only inserted on those pages requiring the Javascript code.

1 Like