0

I need to load VueJS dynamically using a script loader but I'm unable to understand why Vue doesn't initialize.

Here's my simple script-loader:

(function( w ){
    var loadJS = function( src, cb ){
        "use strict";
        var ref = w.document.getElementsByTagName( "script" )[ 0 ];
        var script = w.document.createElement( "script" );
        script.src = src;
        script.async = true;
        ref.parentNode.insertBefore( script, ref );
        if (cb && typeof(cb) === "function") {
            script.onload = cb;
        }
        return script;
    };
    // commonjs
    if( typeof module !== "undefined" ){
        module.exports = loadJS;
    }
    else {
        w.loadJS = loadJS;
    }
}( typeof global !== "undefined" ? global : this ));

In the browser console, I invoke the script-loader using this:

loadJS('https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.min.js')

I can see VueJS being requested in the network panel, but typing Vue into the console gives me Uncaught ReferenceError: Vue is not defined error.

I'm able to load other libs using the same script loader but not Vue. I'm baffled.

7
  • Why don't you use a robust loader like SystemJS or RequireJS instead of rolling your own? Commented Sep 30, 2018 at 10:21
  • I guess I could but that seems to have the same issue: stackoverflow.com/questions/50396625/… Commented Sep 30, 2018 at 10:25
  • Without seeing how you use Vue in your app, it's tough to say. I imagine something like this would at least work though SystemJS.import("https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.min.js").then(({default: Vue}) => window.Vue = Vue); Commented Sep 30, 2018 at 10:30
  • Alternately with RequireJS: require(["https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.min.js"], Vue => window.Vue = Vue); Commented Sep 30, 2018 at 10:32
  • 1
    You're doing script.async = true;. How are you including the script that consumes Vue? I suspect you're not loading that asynchronously as well, so it gets executed before Vue is available. The other cause might be that loading Vue as a module won't automatically expose a global Vue variable. Commented Sep 30, 2018 at 10:38

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.