22

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")
Penny Liu
  • 11,885
  • 5
  • 66
  • 81
Robin Heggelund Hansen
  • 4,766
  • 6
  • 34
  • 52

2 Answers2

28

This works for me in Firefox:

var DOMContentLoaded_event = document.createEvent("Event")
DOMContentLoaded_event.initEvent("DOMContentLoaded", true, true)
window.document.dispatchEvent(DOMContentLoaded_event)
Inversion
  • 1,005
  • 13
  • 19
23

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

window.document.dispatchEvent(new Event("DOMContentLoaded", {
  bubbles: true,
  cancelable: true
}));
hankchiutw
  • 1,288
  • 1
  • 9
  • 15