How to capture document.ready or window.load events in Gatsby How to capture document.ready or window.load events in Gatsby reactjs reactjs

How to capture document.ready or window.load events in Gatsby


I think you should add these event listeners in the gatsby-browser.js:

// gatsby-browser.js// ES6export const onClientEntry = () => {  window.onload = () => { /* do stuff */ }}// or commonjsexports.onClientEntry = () => {  window.onload = () => { /* do stuff */ }}

You don't have to check for window there because this file is only run on the client side. Here's the full list of available hooks.

also AFAIK document doesn't have a ready event, it's a jQuery thing. You might be interested in DOMContentLoaded event, though there's some small different between that and jQuery's ready IIRC.


This is what I did until now however it doesn't seem very appropriate:

This is perfectly legitimate code imho:

componentDidMount = () => {  window.addEventListener("load", this.myEventHandler);  ...

EDIT

Thinking about this, by the time componentDidMount has run, window "load" and document "ready" will already have fired... so it is a bit pointless.

https://codesandbox.io/s/n43z5x00j4

You can just use componentDidMount to check that the DOM has loaded and not bother with the other two events.