Home > Enterprise >  It seems I cannot use JS code from CDN import
It seems I cannot use JS code from CDN import

Time:11-05

I have two HTML buttons, each linked to a specific JavaScript function. The first button triggers a function codded like so:

function add() {
  var newScript = document.createElement("script");
  newScript.src = "https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.js";
  document.head.appendChild(newScript);
}

The second button triggers the following function:

function draw() {
  const ctx = document.getElementById('myChart').getContext('2d');
  const myChart = new Chart(ctx, {
    type: 'bar',
    data: {
        labels: ['Red', 'Blue', 'Yellow', 'Green', 'Purple', 'Orange'],
        datasets: [{
            label: '# of Votes',
            data: [12, 19, 3, 5, 2, 3],
            backgroundColor: [
                'rgba(255, 99, 132, 0.2)',
                'rgba(54, 162, 235, 0.2)',
                'rgba(255, 206, 86, 0.2)',
                'rgba(75, 192, 192, 0.2)',
                'rgba(153, 102, 255, 0.2)',
                'rgba(255, 159, 64, 0.2)'
            ],
            borderColor: [
                'rgba(255, 99, 132, 1)',
                'rgba(54, 162, 235, 1)',
                'rgba(255, 206, 86, 1)',
                'rgba(75, 192, 192, 1)',
                'rgba(153, 102, 255, 1)',
                'rgba(255, 159, 64, 1)'
            ],
            borderWidth: 1
        }]
    },
    options: {
        scales: {
            y: {
                beginAtZero: true
            }
        }
    }
});

In function number 2, I am using a sample from www.chartjs.org. To work, it needs the page to have loaded the script referred to in the first function.

After clicking on the button 1 then on the button 2, I am expecting to see in my head element a script element, src=https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.js, which I do see, via the browser console.

On my page, I am expecting to see (after clicking on my second button) a graph, produced by the ChartJS code. This very element is missing. Instead, I have an error in my console, saying: 'Chart is not defined at HTMLButtonElement.draw'

Why do I have this error? Why is my chart not showing up?

Thank you for stopping by :) (y)

CodePudding user response:

One hacky solution is to just include the entire script in your function. i.e.

function add() {
/*!
 * Chart.js v2.9.4
 * https://www.chartjs.org
 * (c) 2020 Chart.js Contributors
 * Released under the MIT License
 */
//The entire contents of https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.min.js pasted here
}

CodePudding user response:

Just add html script element, before the your script is evaluated.

<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.js"></script>
<script>
function draw() {
    // your draw function 
} 
</script>
  • Related