25

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
  • 15,447
  • 5
  • 79
  • 98
Robin Heggelund Hansen
  • 4,906
  • 6
  • 37
  • 54

2 Answers2

34

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,546
  • 1
  • 12
  • 15
  • The `cancelable: true` is not necessary since the `DOMContentLoaded` event on either [window](https://developer.mozilla.org/en-US/docs/Web/API/Window/DOMContentLoaded_event) or [document](https://developer.mozilla.org/en-US/docs/Web/API/Document/DOMContentLoaded_event) is not cancelable when it's dispatched by browser, and you may also want to dispatch the [window.onload event](https://stackoverflow.com/questions/588040/window-onload-vs-document-onload) that is also not cancelable too. – n0099 Oct 29 '22 at 06:57
  • and this can't trigger any callback within [`$(function)` from jquery](https://learn.jquery.com/using-jquery-core/document-ready/) since it will only be invoked one time after the event listener being removed: https://github.com/jquery/jquery/blob/3.6.1/src/core/ready.js?rgh-link-date=2022-10-29T07%3A31%3A12Z#L62 – n0099 Oct 29 '22 at 07:32
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,131
  • 13
  • 19