require.js的好处1

一个例子就能说明一大好处

index.html

<!DOCTYPE html>
<html>
    <head>
        <script type="text/javascript" src="a.js"></script>
    </head>
    <body>
      <span>body</span>
    </body>
</html>

 a.js

function fun1(){
  alert("it works");
}

fun1();

 这是调用一个js文件的一般做法

require.js的做法是

index.html

<!DOCTYPE html>
<html>
    <head>
        <script type="text/javascript" src="require.js"></script>
        <script type="text/javascript">
            require(["a"]);
        </script>
    </head>
    <body>
      <span>body</span>
    </body>
</html>

 a.js

define(function(){
    function fun1(){
      alert("it works");
    }

    fun1();
})

 这两种做法的差别是,一般写法是要等弹出框“it works”并点击确定,页面才会渲染出“body”,require.js的情况是肉眼观察弹出框的出现和页面渲染同时进行,因为require调用模块是异步进行的

猜你喜欢

转载自xiaoxiaoher.iteye.com/blog/2389403