Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Manually dispatchEvent DOMContentLoaded

Tags:

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") 
like image 839
Robin Heggelund Hansen Avatar asked Feb 05 '12 21:02

Robin Heggelund Hansen


People also ask

What triggers DOMContentLoaded?

The DOMContentLoaded event fires when the initial HTML document has been completely loaded and parsed, without waiting for stylesheets, images, and subframes to finish loading.

Does DOMContentLoaded wait for scripts?

DOMContentLoaded does not wait for stylesheets to load, however deferred scripts do wait for stylesheets, and DOMContentLoaded queues behind deferred scripts. Also, scripts which aren't deferred or async (e.g. <script> ) will wait for already-parsed stylesheets to load.

When should I use DOMContentLoaded?

The DOMContentLoaded event is a useful event that can make a big impact on the performance of your pages, hence this example. It fires when the HTML and scripts that make up the page have loaded, but not necessarily the images or CSS.

What is DOMContentLoaded Chrome?

DOMContentLoaded indicates when the browser has finished parsing the document (but other resources such as images and stylesheets may/may not have been downloaded). It is represented as a blue line. The load event fired will occur once all the initial resources (images, stylesheets, JavaScript) have been downloaded.


1 Answers

This works for me in Firefox:

var DOMContentLoaded_event = document.createEvent("Event") DOMContentLoaded_event.initEvent("DOMContentLoaded", true, true) window.document.dispatchEvent(DOMContentLoaded_event) 
like image 173
Inversion Avatar answered Oct 05 '22 12:10

Inversion