We have essentially this in a large scale React SPA:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<div id="root"></div>
<script src="/application.js"></script>
<script src="a-third-party-remote-script.js"></script>
<script>var configFor3rdPartyStuff = {keyvalstuff}</script>
</body>
</html>
Inside application we might do basically this (in some deeply nested import):
const Popup = () => {
useEffect(() => {
const div = document.createElement('div')
div.textContent = 'hello world'
document.body.appendChild(div)
}, [])
}
ReactDOM.render(<Popup />, document.querySelector('#root'))
The document.body is >99% of the time present, but in a few cases (< 50 cases over 2 months, with many thousands of page views per day), the document.body seems to be null, as rollbar is catching and logging an error right where we are doing document.body.appendChild(div). Is this because we need to wait for the window.onload event? Or something else?
Two potential solutions come to mind. One is to dynamically load the script elements programmatically, after window.onload. The other is to wait for window.onload inside the app entry point, making the onload callback do ReactDOM.render.... As I can't reproduce this issue I am not sure it is the solution. What do you think should be done for the ideal architecture to prevent this error?
So far, the error only seems to be occurring on Chrome for Windows, and Chrome Mobile WebView on Android, if that makes a difference.
Is it possible that the customer closes the browser while the app is still loading, and then when they reopen the app, the code that loaded runs, but might be cut off, and it runs before the body is ready? I don't think so but trying to think outside the box.