我有一个HTML页面:
<!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/babel-standalone@6.15.0/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>
浏览器如何查看类型为“ text / babel”的脚本,并让babel转换代码? React库何时何地可以执行JavaScript代码?
解决方法:
Take a look at the unminified source for Babel.js 6.1.19
在该文件中搜索“文本/ babel”.看看在runScripts()中使用它的地方吗?
该函数太长,无法在此处完整包含,它包含以下注释:
/**
* Load, transform, and execute all scripts.
*/
此功能是魔术的起点.但是,我们如何启动runScripts?搜索对该函数的引用.它仅位于几个景点:
if (global.addEventListener) {
global.addEventListener("DOMContentLoaded", runScripts, false);
} else if (global.attachEvent) {
global.attachEvent("onload", runScripts);
}
换句话说,Babel将runScripts附加为DOM的onload事件的事件处理程序.该事件何时发出?让我们检查一下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
因此,Babel的事件处理程序在DOM完成加载后运行.至此,所有脚本均已加载.那时,Babel扫描脚本,找到具有正确类型的脚本标签,然后执行操作.