Sometimes it’s difficult to describe the problem to other people if you met a problem. I continue to write articles for two purposes. The first one is that I could practice my English and writing, and it drives me to dig more tech. The second point is the article I have written could help others. Back to this article's topic.
Between ComponentDidMount and the Callback of DOMContentLoaded, Which is the Firstly Execute? Here is the snippet code below.
<!DOCTYPE html> <html> <head> <script crossorigin src="https://unpkg.com/react@16/umd/react.production.min.js"></script> <script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.production.min.js"></script> <script> document.addEventListener('DOMContentLoaded', function(event) { console.log('DOMContentLoaded'); }); </script> </head> <body> <div id="root"></div> <script type="text/javascript"> class App extends React.Component { componentDidMount() { console.log('componentDidMount'); } render() { return React.createElement('div'); } } const rootElement = document.getElementById("root"); ReactDOM.render(React.createElement(App), rootElement); </script> </body> </html>
As we know, ComponentDidMount executed after the component mounted. We thought the DOM tree have already.
It’s easy to explain if you know the browser parse HTML order and DOMContentLoaded. When the renderer process received HTML data, the main thread begins to parse the text string (HTML) and turn it into a Document Object Model (DOM).
From top to bottom.
Here is why ComponentDidMount firstly execute. We should understand the difference between the React component mounted and dom ready. React ComponentDidMount immediately execute after the wrapper have already added to the dom tree. DOMContentLoaded's callback will execute after all dom had already added to the dom tree. That's the difference all and part.