0

It is well known to everyone that using defer is an efficient way to minimize the loading time of a website.

In my project, I am using Vue (included in the header using defer) and in a circumstance, I want to use a component that is created by another person. When I try to do Vue.Component(...) in the body of the HTML, it says Vue is undefined. It seems that my script in the body is running before the external script has been loaded. Is there any way to fix this issue?

I tried to do document.onload, but the function itself is not working.

PS: Just to be clear, the external script is referring to my js file where Vue is defined and I am not talking about the third party library at all.

1 Answer 1

5

Instead of document.onload you need to use window.onload or document.body.onload.

But an even better way is to wait for the load event on <script> tag:

<html>
    <head>
        <script id="vue-script" src="vue.js" charset="utf-8" defer></script>
    </head>
    <body>
        <script type="text/javascript">
            function onVueLoaded() {
                Vue.render();
            }

            if ('Vue' in window) {
                onVueLoaded();
            } else {
                var script = document.getElementById('vue-script');
                script.addEventListener('load', onVueLoaded);
                script.addEventListener('error', () => console.warn('failed to load Vue.js'));
            }
        </script>
    </body>
</html>

Here I also added a handler for the error event if you wanted to explicitly handle loading errors.

Sign up to request clarification or add additional context in comments.

Comments

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.