Is there a way to tell when your react app page is done loading the page / assets?
Asked Answered
O

2

20

I have a script in my react app that I would like to run after the page is completely done loading.

I've tried listening for the window load like this in componentDidMount / componentDidUpdate:

document.onreadystatechange = function () {
  if (document.readyState === 'complete') {
    // do stuff
  }
}

This works once when the app is first loaded, but not on subsequent loads.

I've also tried this:

window.onload = function () { alert("It's loaded!") }

But also the same result.

I've tried adding this alert in a before hook on the history:

browserHistory.listen((location) => { 
  window.onload = function () { alert("It's loaded!") }
}

This only works after I'm navigating though. Is there an after hook for browserHistory that will run after the page is loaded?

Bottomline, I'd like to know when the page is loaded in a react app on route change and on refresh so I can execute a script.

Thanks

Ozzy answered 30/8, 2019 at 15:26 Comment(2)
ReactDOM.render(<MyElement />, document.getElementById('root'), () => { console.log('page is loaded'); }) The function runs once the page is loaded.Deterrence
This approach works but it only fires when the page is refreshed or accessed via url. How would get this to console.log after navigating to the page, and after the page is loaded too?Ozzy
A
16

As mentioned in another answer, you can use the useEffect hook which is called automatically when the component is mounted in the DOM. But the fact that the component is mounted on the page does not mean that the page is fully loaded.

In the hook I am adding a few lines of code to check if the page is fully loaded, inspired by this answer:

  // This will run one time after the component mounts
  useEffect(() => {
    // callback function to call when event triggers
    const onPageLoad = () => {
      console.log('page loaded');
      // do something else
    };

    // Check if the page has already loaded
    if (document.readyState === 'complete') {
      onPageLoad();
    } else {
      window.addEventListener('load', onPageLoad, false);
      // Remove the event listener when component unmounts
      return () => window.removeEventListener('load', onPageLoad);
    }
  }, []);
Awad answered 18/10, 2022 at 19:57 Comment(1)
This was very helpful in trying to figure out what run of useEffect was on a fresh page load, vs was just a component mounting.Legacy
C
4

You can use React's class component lifecycle method componentDidMount() (More info here).

Alternatively, you can use the useEffect() hook in a functional component, like this:

 useEffect(() => console.log('mounted'), []);

The code inside useEffect() will run after the component is mounted.

Chemosmosis answered 30/8, 2019 at 15:33 Comment(1)
The component could be mounted and the page still loading...Jansen

© 2022 - 2024 — McMap. All rights reserved.