Manually dispatchEvent DOMContentLoaded
Asked Answered
T

2

27

Is there any way to manually fire the DOMContentLoaded event?

I'm trying to write a unit-test for some client-side JavaScript which does some stuff on the DOMContentLoaded event.

The following did not work:

document.dispatchEvent("DOMContentLoaded")

or

document.body.dispatchEvent("DOMContentLoaded")
Toggle answered 5/2, 2012 at 21:42 Comment(0)
E
29

This works for me in Firefox:

var DOMContentLoaded_event = document.createEvent("Event")
DOMContentLoaded_event.initEvent("DOMContentLoaded", true, true)
window.document.dispatchEvent(DOMContentLoaded_event)
Essary answered 22/2, 2012 at 21:24 Comment(0)
F
39

Since initEvent is deprecated, it's better to use Event constructor like this:

window.document.dispatchEvent(new Event("DOMContentLoaded", {
  bubbles: true,
  cancelable: true
}));
Foreign answered 9/4, 2018 at 2:48 Comment(2)
The cancelable: true is not necessary since the DOMContentLoaded event on either window or document is not cancelable when it's dispatched by browser, and you may also want to dispatch the window.onload event that is also not cancelable too.Assonance
and this can't trigger any callback within $(function) from jquery since it will only be invoked one time after the event listener being removed: github.com/jquery/jquery/blob/3.6.1/src/core/…Assonance
E
29

This works for me in Firefox:

var DOMContentLoaded_event = document.createEvent("Event")
DOMContentLoaded_event.initEvent("DOMContentLoaded", true, true)
window.document.dispatchEvent(DOMContentLoaded_event)
Essary answered 22/2, 2012 at 21:24 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.