'Understanding the "type" attribute in a <script> tag

I'm seeking a clear explanation of the type attribute inside an html <script> tag. For most my career as a web developer, my instructions from the internet were:

  • Just write <script type='text/javascript'> and then put javascript inside of it.
  • In html5, just write <script> because the text/javascript is the default.

And for the longest time I was naive and just did what I was told. Now I'm learning ReactJS, and there's a new set of instructions:

  • Include the babel script at the top of your file
  • Now write <script type="text/babel">
  • Voila! Now you can write something that looks a lot like Javascript inside that tag, but it has a bunch of cool extra features in addition.

I want to understand the magic behind adding type='text/babel' to a script tag. I know that javascript is the only language that actually runs in a browser, so what is the relationship between that extra attribute, the babel script and the code you write inside. Does that tag somehow find the babel script and do something to it? Is this a fundamental browser/js feature that allows preprocessing text in a script tag before being executed by javascript? What else should I know?

Demystification is the goal of this question.



Solution 1:[1]

No, the browser does not do anything to type=text/babel. Mainstream browsers only understand supported MIME types in the type attribute, and always default to ECMAScript (JavaScript). Most browsers, as of today, are still not fully ES6-compatible.

Babel is a compiler that compiles any ES6 code enclosed within the <script type="text/babel"> into a ES5 JavaScript, a version that most modern browsers can understand. When you run babel code, the browser simply ignores the babel scripts. Babel is the library that looks for it, transform code into ES5 and tells the browser to run it.

Solution 2:[2]

If the browser has the MIME type registered (as (historically) might be the case for VBScript or PerlScript) then it will be run, by the browser, through the appropriate parser/compiler/interpreter/etc.

Otherwise, it is just an element in the DOM with a text node inside it.

Other code, e.g. written in JavaScript, can find the DOM element, read the content of it, and then act on it. This is what Babel does.

Solution 3:[3]

Simple:

Browser engine just understand type="type/javascript" then run JS code.

You can add your custom type like type="type/f*ckjs" but browser skip script element ! :)

When add transformer library to HTML file like bablejs, babeljs decide read any <script> tags with define explicit type like type/babel or type/jsx and read src file and transform code to JS executable.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 light
Solution 2 Quentin
Solution 3 Moslem Shahsavan