>  Q&A  >  본문

javascript - 关于js 异步加载问题?

代码一

var math = require('math');
math.add(2,3);

代码二

require(['math'],function(math){
    math.add(2,3);
});

请问大神:代码二的写法比代码一的写法优点有什么,如果是异步加载的话,那么不加载完math这个模块,又怎么去调用add()这个方法呢??新人求教,求轻喷!!!

PHP中文网PHP中文网2749일 전370

모든 응답(2)나는 대답할 것이다

  • 阿神

    阿神2017-04-10 14:43:34

    没有用过requirejs,不过我通常使用seajs,概念应该一致的。

    seajs中同步异步加载方式如下

    //同步
    var module = require('math');
    module.add(3);
    //to do another code
    
    //异步
    require.async('math',function(math){
      math.add(3);
    });
    //to do another code
    

    在上面中,同步是先加载要引入的的文件,之后顺序执行下面的代码。

    异步则是先执行下面的代码,然后在加载完成模块后,在下一事件循环中,再次执行callback中的方法

    在执行时,require的文件,是先行进行下载的,然后把对象按路径名缓存在seajs中的一个对象中的。async是在执行时,才去下载。

    회신하다
    0
  • 天蓬老师

    天蓬老师2017-04-10 14:43:34

    应该这么写:

    代码一

    var math = require('math');
    math.add(2,3);
    
    do_some_onther_things(); // ****
    

    代码二

    require(['math'],function(math){
        math.add(2,3);
    });
    
    do_some_onther_things(); // ****
    

    代码三

    require(['math'],function(math){
        math.add(2,3);
        do_some_onther_things(); // ****
    });
    

    明白了吗?

    회신하다
    0
  • 취소회신하다