Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I am relatively new to the Gatbsy framework and I am trying to figure out a way to toggle classes on some elements on DOMContentLoaded or on window.load, to animate them as soon as the user can see the screen.

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

componentDidMount = () => {
  if (typeof window === "undefined") return
  window.addEventListener("load", this.myEventHandler)
  // or
  if (typeof document === "undefined") return
  document.addEventListener("DOMContentLoaded", this.myEventHandler)
}

Is there a better way of doing this?

Thank you in advance.

like image 353
Harry Theo Avatar asked Mar 19 '19 21:03

Harry Theo


People also ask

What is difference between window load and document ready?

The key difference between $(document). ready() and $(window). load() event is that the code included inside onload function will run once the entire page(images, iframes, stylesheets,etc) are loaded whereas the $(document). ready() event fires before all images,iframes etc.

Which event is commonly used to trigger scripts when a page has finished loading?

The onload event occurs when an object has been loaded. onload is most often used within the <body> element to execute a script once a web page has completely loaded all content (including images, script files, CSS files, etc.).

What is it called when a page loads an event?

The load event is fired when the whole page has loaded, including all dependent resources such as stylesheets and images. This is in contrast to DOMContentLoaded , which is fired as soon as the page DOM has been loaded, without waiting for resources to finish loading.

What is Gatsby browser file?

js API file. The file gatsby-browser. js lets you respond to actions within the browser, and wrap your site in additional components. The Gatsby Browser API gives you many options for interacting with the client-side of Gatsby.


1 Answers

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

// gatsby-browser.js
// ES6
export const onClientEntry = () => {
  window.onload = () => { /* do stuff */ }
}

// or commonjs
exports.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.

like image 154
Derek Nguyen Avatar answered Sep 24 '22 03:09

Derek Nguyen