“加载"具有异步和/或延迟的脚本事件 [英] "Load" event on script with async and/or defer
问题描述
嵌入如下脚本时:
<script src="..." async defer></script>
是否有办法知道何时完成加载?
Is there a way to know when they're finished loading?
通常,当调用window.load
事件时,人们希望所有脚本也准备就绪.但是我不知道用async
或defer
加载它们是否仍然成立.我已经在线阅读了一些文档,但找不到关于此问题的任何结论.
Usually when the window.load
event is called, one would expect all scripts to be ready as well. But I don't know if that still holds when you load them with async
or defer
. I've read some docs online but couldn't find anything conclusive on this issue.
推荐答案
答案:
您可以利用onload
事件属性,以便在脚本加载后执行某种回调.
示例:
在下面的示例html脚本元素中,当脚本(来自google api的jquery库)完成异步加载时,会弹出警告,提示资源已加载"
Answer:
You could take advantage of the onload
event attribute in order to perform some kind of callback once your script is loaded.
Example:
In the example html script element below when the script (jquery library from google api) finishes loading asynchronously, an alert will pop up saying 'resource loaded'.
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js" async defer onload="alert('resource loaded');">
注意:src脚本将非常快速地加载,因为它是由google托管的,因此,最有可能在页面/DOM加载后立即显示弹出窗口.
window.onload
在文档加载前等待一切加载,而document.onload
在文档对象模型(DOM)准备就绪时启动.
window.onload
waits for everything to load before firing whereas document.onload
fires when the Document Object Model (DOM) is ready.
因此,如果您有异步脚本,将首先执行document.onload
,而window.onload
将等待这些异步脚本完成加载.
So if you've got async scripts document.onload
will execute first while window.onload
will wait for those asynchronous scripts to finish loading.
总结:
-
window.onload
将考虑到异步脚本. -
document.onload
不会考虑异步脚本.
window.onload
will take async scripts into account.document.onload
will not take async scripts into account.
这篇关于“加载"具有异步和/或延迟的脚本事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!