javascript 手动 dispatchEvent DOMContentLoaded

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9153314/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 05:45:49  来源:igfitidea点击:

Manually dispatchEvent DOMContentLoaded

javascriptdomdom-events

提问by Robin Heggelund Hansen

Is there any way to manually fire the DOMContentLoadedevent? I'm trying to write a unit-test for some client-side JavaScript which does some stuff on the DOMContentLoadedevent.

有没有办法手动触发DOMContentLoaded事件?我正在尝试为一些客户端 JavaScript 编写一个单元测试,它在DOMContentLoaded事件上做一些事情。

The following did not work:

以下方法无效:

document.dispatchEvent("DOMContentLoaded")or document.body.dispatchEvent("DOMContentLoaded")

document.dispatchEvent("DOMContentLoaded")或者 document.body.dispatchEvent("DOMContentLoaded")

回答by Inversion

This works for me in Firefox:

这在 Firefox 中对我有用:

var DOMContentLoaded_event = document.createEvent("Event")
DOMContentLoaded_event.initEvent("DOMContentLoaded", true, true)
window.document.dispatchEvent(DOMContentLoaded_event)

回答by Hank Chiu

Since initEventis deprecated here, it's better to use Eventcontructor like this:

由于此处initEvent已弃用,因此最好使用这样的构造函数:Event

window.document.dispatchEvent(new Event("DOMContentLoaded", {
  bubbles: true,
  cancelable: true
}));