且构网

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

当脚本是从加载的脚本动态创建的DOM节点时,脚本的onload和window.onload的顺序是否正确定义?

更新时间:2023-12-04 22:46:34

是的,您看到的输出是有保证的,因为 load 事件在资源及其依赖项时触发资源已加载完毕。在下载包含下载内容的每个元素并准备就绪(包括脚本和图像)之前,窗口不会完全加载。因此,必须在窗口加载之前先加载< script>

Yes, the output you see is guaranteed, because the load event is fired "when a resource and its dependent resources have finished loading." The window will not be fully loaded until every element with something to download is downloaded and ready, including scripts and images. So, the <script> has to load before the window loads.

存在一个动态创建的脚本的事实不会产生任何效果(假设 main 在窗口完全加载之前被调用,例如您的代码)-插入DOM后,它现在就是窗口所依赖的东西,因此必须 load 才可以在窗口之前完成。

The fact that there's a script which is created dynamically won't have an effect (assuming that main is called before the window is fully loaded, like in your code) - once inserted into the DOM, it's now something the window depends on, and so must load before the window does.