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
ReactDOM. render(<MyElement />, document. getElementById('root'), () => { console. log('page is loaded'); }) The function runs once the page is loaded.
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”.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With