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

30.6k views Asked by At

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

2

There are 2 answers

1
Yuliya Plotka On

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.

1
Dayron Gallardo On

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);
    }
  }, []);