5

I got a HTML page:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8" />
    <title>Hello World</title>
    <script src="https://unpkg.com/react@16/umd/react.development.js"></script>
    <script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
    <script src="https://unpkg.com/[email protected]/babel.min.js"></script>
  </head>
  <body>
    <div id="root"></div>
    <script type="text/babel">
      ReactDOM.render(
        <h1>Hello, world!</h1>,
        document.getElementById('root')
      );
    </script>
  </body>
</html>

How browser sees the script with type "text/babel" and lets babel transpile the code? When and where JavaScript code appears to be executed by React libraries?

1 Answer 1

9

Take a look at the unminified source for Babel.js 6.1.19

Search that file for "text/babel". See where it's used in runScripts()?

That function, which is too long to include here in its entirety, contains comments such as:

/**
 * Load, transform, and execute all scripts.
 */

This function is where the magic starts. But how do we launch runScripts? Search for references to that function. It is located in only a few spots:

if (global.addEventListener) {
    global.addEventListener("DOMContentLoaded", runScripts, false);
} else if (global.attachEvent) {
    global.attachEvent("onload", runScripts);
}

In other words, Babel is attaching runScripts as an event handler for the DOM's onload event. When is that event emitted? Let's check MDN:

The load event fires at the end of the document loading process. At this point, all of the objects in the document are in the DOM, and all the images, scripts, links and sub-frames have finished loading.

There are also Gecko-Specific DOM Events like DOMContentLoaded and DOMFrameContentLoaded (which can be handled using EventTarget.addEventListener()) which are fired after the DOM for the page has been constructed, but do not wait for other resources to finish loading.

https://developer.mozilla.org/en-US/docs/Web/API/GlobalEventHandlers/onload

So, Babel's event handler is run after the DOM has completed loading. All scripts are loaded by this point. At that time, Babel scans the scripts, finds the script tags with the right type, and does its thing.

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.