[Vuejs]-How to add external js file in Nuxt for a specific page?

0👍

I realized, after creating a sandbox, that it does indeed load the script when you navigate to it. The problem is if you try to load that external libraries methods/functions/variables before the script is actually loaded (e.g. on a mounted() call). I solved it like this:

As an example, if you’d wish to load jQuery for a specific page, this will fail:

mounted () {
    jQuery('.element').hide();
}

However, you can set up an interval to check whenever jQuery is loaded in, like so:

mounted () {
    const awaitScriptInterval = setInterval(() => { // set an interval to check when script is loaded
        if (typeof jQuery === 'undefined') { // script is not yet loaded in
            return;
        }

        clearTimeout(awaitScriptInterval); // clear the interval, so we don't continuously check 

        jQuery('.element').hide(); // use your external library
    }, 500); // the interval in milliseconds to check
}

See this article on how to load an external script/style: https://nuxtjs.org/faq/#local-settings

Leave a comment