external script doesn't always loads when we navigate between components nuxt 3
Asked Answered
I

2

2

external script doesn't always loads when we navigate between components nuxt 3 , i have created component dashboard/index.vue added this code

useHead({
    script: [
        {
            src: 'https://code.highcharts.com/highcharts.js',
            type: 'text/javascript',
            async: true,
            body: true
        },
    ],
});

this it the function i am using in onMounted

const initializeCharts = () => {
    window.Highcharts.chart('highchart-1', {
        chart: {
            type: 'spline',
            height: 310
        },
        title: {
            text: 'Monthly Average Temperature'
        },
        xAxis: {
            categories: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
                'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
            accessibility: {
                description: 'Months of the year'
            }
        },
        yAxis: {
            title: {
                text: 'Temperature'
            },
            labels: {
                format: '{value}°'
            }
        },
        tooltip: {
            crosshairs: true,
            shared: true
        },
        plotOptions: {
            spline: {
                marker: {
                    radius: 4,
                    lineColor: '#666666',
                    lineWidth: 1
                }
            }
        },
        series: [{
            name: 'Tokyo',
            marker: {
                symbol: 'square'
            },
            data: [5.2, 5.7, 8.7, 13.9, 18.2, 21.4, 25.0, {
                y: 26.4,
                marker: {
                    symbol: 'url(https://www.highcharts.com/samples/graphics/sun.png)'
                },
                accessibility: {
                    description: 'Sunny symbol, this is the warmest point in the chart.'
                }
            }, 22.8, 17.5, 12.1, 7.6]

        }, {
            name: 'Bergen',
            marker: {
                symbol: 'diamond'
            },
            data: [{
                y: 1.5,
                marker: {
                    symbol: 'url(https://www.highcharts.com/samples/graphics/snow.png)'
                },
                accessibility: {
                    description: 'Snowy symbol, this is the coldest point in the chart.'
                }
            }, 1.6, 3.3, 5.9, 10.5, 13.5, 14.5, 14.4, 11.5, 8.7, 4.7, 2.6]
        }]
    });

when we navigate from one page to dashboard page it doesn't loads , when we reload the dashboard page then it works fine as expected

i have tried adding onMounted, onBeforeUpdate and many other lifecycle hooks but at the end i see the same error, i am using nuxt3 here is the stackblitz code

https://stackblitz.com/edit/github-kqvufh

Instrumental answered 18/7, 2023 at 1:21 Comment(5)
Are you using NuxtLink to navigate from one page to another? Your codes are working. You may need to check what's causing the issue or add more info or codes related to the issue.Birthmark
updated the code but basically the issue is the script is not loading , i can not see that script in head or before body , but when i reload the page then everything is perfect ... i am using nuxlink yesInstrumental
Hey, can you setup a minimal reproduction on stackblitz so It becomes easier for me and others to check the code and try out solutions that may help you?Cytotaxonomy
@MuhammadMahmoud yes shared :)Instrumental
@samairali I'll try it out as soon as I could and get back to youCytotaxonomy
C
3

The error happens because your using the initializeCharts in the page onMounted hook which may happen before fetching the script from the CDN. This leads to initializeCharts not finding the window.Highcharts provided by the script.

The solution is ensure running the function only after the script is fetched. This can be done by calling initializeCharts inside the onload hook in useHead like the following

useHead({
  script: [
    {
    src: 'https://code.highcharts.com/highcharts.js',
    onload: () => { initializeCharts() },
    }
  ]
});

onMounted(() => {
  // This is no longer needed and can be removed
  // initializeCharts(); 
});

Check this Stackblitz Link with the applied changes, you'll find the script tag present in both cases (directly opening the dashboard page or naviagting to it from the index page using the link)

Cytotaxonomy answered 21/7, 2023 at 11:13 Comment(8)
no not exactly , the issue is it is not loading the highcart.js script when we navigate from one page to other , if we refresh the page everything works .. make sense ?Instrumental
yes, because on refereshing the page loads the scripts first including the highchart and then gets rendered on the page. When visiting the index page then navigating to dashboard the page is already there but the script is yet to be loaded, that's the problem. Have you tried my solution and didn't work?Cytotaxonomy
yes i have tried your solution , it think the issue is not clear to you :) the script that is the link code.highcharts.com/highcharts.js you will not be able to see it in the inspect element in the browser when you navigate from home to dashboard , but when you reload the dashboard page then you can see this <script src="code.highcharts.com/highcharts.js"> , hope it will be clear now for youInstrumental
@samairali It's there my friend how else would the chart appear. After updating the code as suggested there's a <script src="https://code.highcharts.com/highcharts.js"></script> when you directly open the dashboard page OR naviagte to it from the index by clicking the dashboard link.Cytotaxonomy
@samairali I've updated the answer with a stackblitz link, check it out and you'll find that the script tag is present in both casesCytotaxonomy
i have copied the exact same thing but it is not working for me .. for the work around i have added head in nuxt config but after that it loads the script on all pages/components i dont want that , for learning i am trying to make it load on specific component ...Instrumental
Have you tried the stackblitz link and found the script in both cases? This means that the problem is on your end and maybe you're doing something wrong at your local deviceCytotaxonomy
I have just written an answer to your question. Your request was a while ago, but maybe it will help you or someone else who might be looking for this answer later.Grodno
G
0

Sometimes it is necessary to add the script at the end of the body. This way, all DOM elements are loaded beforehand. In your case, it may even be important that your script is loaded after the DOM element with the ID appears.

I think especially in your case you should store initializeCharts as a script file and load it dynamically with useHead() at the end of the body.

useHead({
  script: [
    {
      src: './path/to/your/script/initializeCharts.js',
      tagPosition: 'bodyClose'
    }
  ]
})
Grodno answered 10/9 at 2:38 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.