Search code examples
vue.jscdnapexcharts

Using ApexCharts imported as CDN in Vue


I'm trying to use vue-apexcharts in my Vue project and I'm trying to import the library via script tags to keep the bundle size down when im building my app.

My code looks something like this:

import Vue from "vue";

export default new Vue({
  data: {},
  components: {},
  created() {
    const apexcharts = document.createElement("script");
    apexcharts.setAttribute("src", "https://cdn.jsdelivr.net/npm/apexcharts");
    document.head.appendChild(apexcharts);

    const vueApexcharts = document.createElement("script");
    vueApexcharts.setAttribute("src", "https://cdn.jsdelivr.net/npm/vue-apexcharts");
    document.head.appendChild(vueApexcharts);
   
  },
});

I'm not sure how to register apexcharts and use it within components once I've added the script tags. Normally I'd find the library reference in the global window but can't find anything there.

Thanks in advance!

Edit

I'm trying to achieve something like this:

import Vue from "vue";

const loadScript = (src) =>
  new Promise((resolve, reject) => {
    const script = document.createElement("script");
    script.setAttribute("src", src);
    script.onload = resolve;
    script.onerror = reject;
    document.head.appendChild(script);
  });

const loadApexCharts = () =>
  loadScript("https://cdn.jsdelivr.net/npm/apexcharts");
const loadVueApexCharts = () =>
  loadScript("https://cdn.jsdelivr.net/npm/vue-apexcharts");

const initVue = () => {
  Vue.component("apexcharts", window.VueApexCharts);
  new Vue({
    data: {},
    components: {},
    created() {
      console.log(window.VueApexCharts, 'log')
    },
  });
};

loadApexCharts()
  .then(loadVueApexCharts)
  .then(initVue)
  .catch((err) => console.warn(err));

But my log returns undefined in this case


Solution

  • ApexCharts needs to be loaded before VueApexCharts, so you have to ensure the script-loading order with Promises. The CDN scripts define window.ApexCharts and window.VueApexCharts, respectively, so once the scripts are loaded, you can register the apexcharts component for use in the app:

    // main.js
    const loadScript = src => new Promise((resolve, reject) => {
      const script = document.createElement('script')
      script.setAttribute('src', src)
      script.onload = resolve
      script.onerror = reject
      document.head.appendChild(script)
    })
    
    const loadApexCharts = () => loadScript('https://cdn.jsdelivr.net/npm/apexcharts')
    const loadVueApexCharts = () => loadScript('https://cdn.jsdelivr.net/npm/vue-apexcharts')
    
    const initVue = () => {
      Vue.component('apexcharts', window.VueApexCharts)
      new Vue({
        render: (h) => h(App)
      }).$mount('#app')
    }
    
    loadApexCharts()
      .then(loadVueApexCharts)
      .then(initVue)
      .catch((err) => console.warn(err))
    

    demo