DOMContentLoaded Callback and ComponentDidMount Execute Order

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.

  • If it’s an HTML tag, add to the dom tree.
  • if it's a script tag, download (usual from preload) and runs it.
  • if it's an inline script tag, run it, call the browser API to bind the DOMContentLoaded event, fire the callback function after DOM ready.
  • continue parse.
  • if it's HTML tags, add to the dom tree.
  • if it's an inline script tag, run it, React component mounted the dom that the id is root.
  • Execute ComponentDidMount after rendered.
  • continue to parse and at the end of </html>
  • Add the DOMContentLoaded's callback function to the task queue.
  • Fire the task and log "DOMContentLoaded”.

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.


This article is original, licensed under a Creative Commons Attribution 4.0 International license