Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 969
zero_cool Avatar asked Aug 30 '19 15:08

zero_cool


People also ask

How do you know if page is fully loaded React?

ReactDOM. render(<MyElement />, document. getElementById('root'), () => { console. log('page is loaded'); }) The function runs once the page is loaded.

How do I check my React app performance?

To use that tool, first, serve your React app in development mode. Load the app in your browser by navigating to localhost:3000 . Open your DevTools, click on the “Performance” tab, if there is nothing like that, you will see “Timeline”, click on it. It is the same as the “Performance”.

Why does my React app take so long to load?

The major cause for this issue is adding too many components into a single bundle file, so the loading of that bundle file might take more time. To avoid this kind of issue, we need to structure our components in an optimized way.


1 Answers

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.

like image 53
Yuliya Plotka Avatar answered Sep 16 '22 16:09

Yuliya Plotka