Search code examples
javascriptdomdom-events

Manually dispatchEvent DOMContentLoaded


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

Solution

  • This works for me in Firefox:

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