I have a script tag in the head html tag. The script should add an event listener when the rest of the index.html file has loaded. Therefore, nothing should run prior to that happening. It is almost the same as adding the script tag at the end of the body except for the browser reading the javascript and causing a little bit of render-blocking.
index.html
<html>
<head>
//meta stuff
<script src="https://unpkg.com/babel-standalone@6/babel.min.js"></script>
<script src="https://unpkg.com/react@15/dist/react.js"></script>
<script src="https://unpkg.com/react-dom@15/dist/react-dom.js"></script>
<script type="text/javascript" src="./code/webapp.js"></script>
</head>
<body>
<noscript>Javascript is not enabled!</noscript>
<div id="root"></div>
</body>
</html>
Here is the console error message I get from React:
Uncaught Error: _registerComponent(...): Target container is not a DOM element.
at invariant (react-dom.js:18118)
at Object._renderNewRootComponent (react-dom.js:9978)
at Object._renderSubtreeIntoContainer (react-dom.js:10069)
at Object.render (react-dom.js:10090)
at App (webapp.js:formatted:28)
The weird part is that the function App() get fired during a window.onload or window.addEventListener('load'). I used this before on my personal website but I had a defer and async on the script tag so maybe that is why it always fired correctly.
webapp.js
...
function App() {
console.log('App loading...');
const reactroot = document.getElementById('root');
var app = React.createElement(WebApp, null);
ReactDOM.render( app, reactroot);
}
window.onload = App;
In case anyone suggest using document.ready(), I am trying to not rely on jQuery. I want to also use this for a production website, not just my personal portfolio. So I can't rely on adding defer/async to the script tag.
Related topics: