RequireJS
require.js加载js文件的好处
- 可以防止JS加载时候阻塞页面渲染(JS运行时候DOM停止渲染的情况)
- 使用require.js调用的方式加载JS,不用在像以前那样多个
<script>
标签引入JS文件
所有代码的目录结构如图
传统的引入
start.html
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="js/require.js"></script>
<script type="text/javascript" src="js/a.js"></script>
</head>
<body>
<p>wsscat</p>
</body>
</html>
传统方法引入可以看到会先弹出alert,内容被阻塞没有渲染
a.js
function cat() {
alert("hello");
}
cat();
require.js的引入
start.html
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="js/require.js"></script>
<script>
require(["js/a"]);
</script>
</head>
<body>
<p>wsscat</p>
</body>
</html>
a.js
define(function () {
function cat() {
alert("hello");
}
cat();
})
现在应require里面写可以避免以前的写法导致alert弹窗时候页面的p
标签内容被阻塞无法渲染
现在这种写法格式是用define定义一个模块,并在页面中调用require方法引入
要注意的是,require接受的是一个数组,它注入的依赖是一个数组,哪怕数组只有一个依赖,而它第二个参数则可以传入一个回调函数,就是党数组中的依赖都加载完毕后,执行这个回调函数