脚本onload发生在JSDOM中的窗口加载之后 [英] Script onload happens after window onload in JSDOM

查看:153
本文介绍了脚本onload发生在JSDOM中的窗口加载之后的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我所学到的一个新问题:

This is a new question arising from what I learnt in: Is order of script onload and window.onload well defined when the script is a DOM node created dynamically from a loaded script?

在上一个问题中,我们了解到当一个窗口正在加载脚本时,任何脚本(直接加载的脚本以及脚本动态加载的脚本)都会先完成加载,然后才会加载将触发 window.onload

In the previous question we learnt that when a window is loading scripts, any scripts (the one directly loaded as well as the ones dynamically being loaded by the script) would finish loading first and only after that the window.onload will fire.

但JSDOM似乎行为不同。

But JSDOM seems to be behaving differently.

这是 loader.js 脚本,它与上一个问题中的脚本相同:

Here is the loader.js script which is same as the one in the previous question:

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()

这是通过JSDOM冒充假窗口的驱动程序代码。

Here is the driver code that pretends to be a fake window via JSDOM.

var jsdom = require('jsdom')
var loader = require('./loader.js')

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

global.window = new jsdom.JSDOM(html, { runScripts: "dangerously", resources: "usable" }).window

这是输出:

$ node fakewindow.js 
window not available yet
window loaded
script loaded

script.onload 事件触发之前触发的 window.onload 事件。为什么JSDOM会考虑加载窗口,即使直接包含在HTML中的脚本加载的动态脚本尚未加载?这是JSDOM中的错误还是相关的W3C标准允许这种行为?

The window.onload event fired before the script.onload event fire. Why did JSDOM consider the window loaded even when a dynamic script loaded by a script directly included in the HTML hadn't loaded yet? Is this a bug in JSDOM or is this behavior allowed by relevant W3C standards?

推荐答案

看起来像JSDOM中的错误。

Seems like a bug in JSDOM.

它似乎在最新版本 13.0.0 中解决,尝试更新JSDOM。

It appears to be solved in the latest version 13.0.0, try updating JSDOM.

我为 jsdom 13 尝试了相同的代码它有效。

I've tried out the same code for jsdom 13 and it works.

window not available yet
script loaded
window loaded

,而 jsdom 11 确实显示了问题:

window not available yet
window loaded
script loaded

这篇关于脚本onload发生在JSDOM中的窗口加载之后的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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