LABJS的运用教程

看到LABjs的时刻是由于当初愿望完成js的异步加载,由于项目的汗青缘由,在页面中须要援用大批的js文件,为了优化页面的加载速率,做了不少的处置惩罚,在运用LABjs的过程当中发明这插件真的很棒,底本页面的初始加载时候须要4S摆布的,在运用LABjs后,页面的加载速率只须要2S-2.3S之间就完成了,它编写简朴明了,固然也有其他东西可以到达与它一样的结果,在此不作比较,愿望人人可以喜好这款插件(它仅仅只要6kb)。
我们先下载LABjs

官网地点http://labjs.com/

比较二者加载的区分

/**
*传统的JS加载体式格局
**/
<script src="framework.js"></script>
<script src="plugin.framework.js"></script>
<script src="myplugin.framework.js"></script>
<script src="init.js"></script>

/**
*采纳LABjs加载
**/
<script>
   $LAB
       .script("framework.js").wait()
       .script("plugin.framework.js")
       .script("myplugin.framework.js").wait()
       .script("init.js").wait();
</script>

我们可以看到,运用LABjs的体式格局代码上显现比较简约。

几个简朴的案例

  • Example 1:

/**
*三个js文件之间不存在依靠,异步加载
**/
$LAB
.script("script1.js")
.script("script2.js")
.script("script3.js")
.wait(function(){ // wait for all scripts to execute first
    script1Func();
    script2Func();
    script3Func();
});
  • Example 2:

/**
*为加载的js文件指定范例
**/
$LAB    
.script({ src: "script1.js", type: "text/javascript" })
.script("script2.js")
.script("script3.js")
.wait(function(){ // wait for all scripts to execute first
    script1Func();
    script2Func();
    script3Func();
});
  • Example 3:

$LAB
.script("script1.js", "script2.js", "script3.js")
.wait(function(){ // wait for all scripts to execute first
    script1Func();
    script2Func();
    script3Func();
});
  • Example 4:

$LAB
.script( [ "script1.js", "script2.js" ], "script3.js")
.wait(function(){ // wait for all scripts to execute first
    script1Func();
    script2Func();
    script3Func();
});

  • Example 5:

$LAB
.script("script1.js").wait() // empty wait() simply ensures execution order be preserved for this script
.script("script2.js") // both script2 and script3 depend on script1 being executed before
.script("script3.js").wait() // but are not dependent on each other and can execute in any order
.script("script4.js") // depends on script1, script2 and script3 being loaded before
.wait(function(){script4Func();});
  • Example 6:

$LAB
.script("script1.js") // script1, script2, and script3 do not depend on each other, 
.script("script2.js") // so execute in any order
.script("script3.js")
.wait(function(){  // can still have executable wait(...) functions if you need to
    alert("Scripts 1-3 are loaded!");
})
.script("script4.js") // depends on script1, script2 and script3 being executed before
.wait(function(){script4Func();});

它还有许多更好玩的用法,人人可以到官网上研讨一番。赶忙试下它的结果,真的会给你带来欣喜的。

    原文作者:_rex_
    原文地址: https://segmentfault.com/a/1190000003771526
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞