首页 > 关于js 异步加载问题?

关于js 异步加载问题?

代码一

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

代码二

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

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


应该这么写:

代码一

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(); // ****
});

明白了吗?


没有用过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是在执行时,才去下载。

【热门文章】
【热门文章】