更新时间:2023-12-05 08:52:04
答案:
您可以利用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.