在加载异步javascript时触发事件

时间:2022-12-03 19:25:24

I'm changing my external javascript resources to be loaded asynchronously to speed up page load. To do this, I'm adding the async property to my script tags:

我正在更改外部javascript资源以异步加载以加快页面加载。为此,我将async属性添加到我的脚本标记:

<script async type="text/javascript" src="external.js"></script>

Right before the end of the body tag I have included this code to perform callbacks:

在body标记结束之前,我已经包含了这段代码来执行回调:

if (typeof(myFuncion) === "function") {
    myFunction();
} else {
    window.onload = myFunction;
}

Basically, if the external.js was cached, when the parser reach this code the myFunction is defined and it will be executed. If not, then it will have to wait for all external resources to be available before calling myFunction. So, myFunction will be waiting for AdSense, Analytics, ... when it really only depends on external.js.

基本上,如果external.js被缓存,当解析器到达此代码时,myFunction被定义并将被执行。如果没有,那么在调用myFunction之前,它必须等待所有外部资源可用。因此,myFunction将等待AdSense,Google Analytics,...当它真的只依赖于external.js。

This doesn't make much sense to me. Any suggestions on how to replace the window.onload for something that would fire when external.js is loaded?

这对我来说没什么意义。关于如何替换window.onload以获取在加载external.js时会触发的内容的任何建议?

1 个解决方案

#1


4  

You should inject a script by JavaScript instead of using a script tag so you have a full control over the load event. See this example below:

您应该通过JavaScript注入脚本而不是使用脚本标记,这样您就可以完全控制load事件。请参阅以下示例:

var script = document.createElement("script");
script.type = 'text/javascript';
script.src = 'external.js';
script.async = true;
document.getElementsByTagName('head')[0].appendChild(script);

script.onload = script.onreadystatechange = function() {
    if (script.readyState ||
        script.readyState === "loaded" || script.readyState === "complete"){
        // Script loaded!

        // So all dependencies are ready, call the desired function now
        myFunction();
    }
}

With this approach, you can capture the event when the script is successfully loaded and trigger an appropriate function afterwards.

使用此方法,您可以在脚本成功加载时捕获事件,然后触发相应的函数。

#1


4  

You should inject a script by JavaScript instead of using a script tag so you have a full control over the load event. See this example below:

您应该通过JavaScript注入脚本而不是使用脚本标记,这样您就可以完全控制load事件。请参阅以下示例:

var script = document.createElement("script");
script.type = 'text/javascript';
script.src = 'external.js';
script.async = true;
document.getElementsByTagName('head')[0].appendChild(script);

script.onload = script.onreadystatechange = function() {
    if (script.readyState ||
        script.readyState === "loaded" || script.readyState === "complete"){
        // Script loaded!

        // So all dependencies are ready, call the desired function now
        myFunction();
    }
}

With this approach, you can capture the event when the script is successfully loaded and trigger an appropriate function afterwards.

使用此方法,您可以在脚本成功加载时捕获事件,然后触发相应的函数。