简体   繁体   English

通过延迟加载外部脚本后运行内部脚本

[英]run internal script after external script has been loaded via defer

It is well known to everyone that using defer is an efficient way to minimize the loading time of a website.众所周知,使用defer是一种减少网站加载时间的有效方法。

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.在我的项目中,我使用的是Vue (包含在使用 defer 的标头中),并且在某种情况下,我想使用由另一个人创建的组件。 When I try to do Vue.Component(...) in the body of the HTML, it says Vue is undefined.当我尝试在 HTML 正文中执行Vue.Component(...)时,它说Vue未定义。 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.我试图做document.onload ,但功能本身不起作用。

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. PS:需要说明的是,外部脚本是指我定义Vue js 文件,我根本不是在谈论第三方库。

Instead of document.onload you need to use window.onload or document.body.onload .取而代之的document.onload你需要使用window.onloaddocument.body.onload

But an even better way is to wait for the load event on <script> tag:但更好的方法是等待<script>标签load事件

<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.如果您想显式处理加载错误,我还为error事件添加了一个处理程序。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM