且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Javascript在加载异步资源后运行内联脚本

更新时间:2023-12-05 09:13:40

将代码包装在:

(function () {
})();

...不会延迟执行。要延迟脚本直到加载资源,请等待窗口加载事件

... does not delay its execution. To delay your script until resources have been loaded, wait to the window load event:


加载事件在结束时触发文件加载过程。此时,文档中的所有对象都在DOM中,所有图像 脚本 ,链接和子帧都已完成加载。

The load event fires at the end of the document loading process. At this point, all of the objects in the document are in the DOM, and all the images, scripts, links and sub-frames have finished loading.

这是一个用< script async> 元素加载jQuery的示例,并显示通过内联脚本的jQuery版本:

Here is an example that loads jQuery with a <script async> element, and shows the jQuery version via the inline script:

window.addEventListener('load', function () {
    console.log(jQuery.fn.jquery);
});

<script async src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

特定 async 脚本已加载,您可以收听自己的加载 ev ENT。为了实现这一目标,如果您将 id 提供给您感兴趣的脚本元素,这可能是最简单的,并且确保内联代码在它之后:

To capture the event when a particular async script has been loaded, you could listen to its own load event. For that to work it is probably the easiest if you give an id to the script element of your interest, and make sure the inline code comes after it:

jq.addEventListener('load', function () {
    console.log(jQuery.fn.jquery);
});

<script id="jq" async src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

请注意 async (和 defer )属性对内联脚本没有影响:

Note that the async (and defer) attributes have no effect on inline scripts:


defer async 属性如果 src 属性不存在,则不得指定s。

The defer and async attributes must not be specified if the src attribute is not present.

他们仅对具有 src 属性的脚本元素产生影响。

They only have an effect on script elements that have the src attribute.