当脚本是从加载的脚本动态创建的DOM节点时,脚本的onload和window.onload的顺序是否正确定义? [英] Is order of script onload and window.onload well defined when the script is a DOM node created dynamically from a loaded script?

查看:102
本文介绍了当脚本是从加载的脚本动态创建的DOM节点时,脚本的onload和window.onload的顺序是否正确定义?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

文件 loader.js

function main()
{
  if (typeof window !== 'undefined') {
    var script = window.document.createElement('script')
    script.src = 'https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.core.min.js'
    script.onload = function () { console.log('script loaded') }
    window.onload = function () { console.log('window loaded') }
    window.document.head.appendChild(script)
  } else {
    console.log('window not available yet')
  }
}

if (typeof module !== 'undefined' && module.exports) {
  exports.main = main
}

main()

文件 window.html

<!DOCTYPE html>
<html>
  <head>
    <title>Test</title>
    <script src="loader.js"></script>
  </head>
  <body>
    <div>Test</div>
  </body>
</html>

打开此HTML页面时控制台输出:

Console output when I open this HTML page:

script loaded
window loaded

我的问题:

在上面的代码中,是否可以保证脚本onload事件始终在窗口onload之前触发?

In the above code, is it guaranteed that the script onload event always fires before the window onload?

推荐答案

是的,您看到的输出是有保证的,因为 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.

这篇关于当脚本是从加载的脚本动态创建的DOM节点时,脚本的onload和window.onload的顺序是否正确定义?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆