从易到难,写一个JavaScript加载器之一
先上代码:
1 (function(global) { 2 var createScript, insertScript, makeLoadQueue; 3 createScript = function(src) { 4 var script; 5 script = document.createElement('SCRIPT'); 6 script.src = "" + src + ".js"; 7 return script; 8 }; 9 insertScript = function(scriptQueue) { 10 var script; 11 script = scriptQueue.shift(); 12 if (script != null) { 13 document.head.appendChild(script); 14 return script.onload = function() { 15 return insertScript(scriptQueue); 16 }; 17 } else { 18 return false; 19 } 20 }; 21 makeLoadQueue = function(loadList) { 22 var loadQueue; 23 loadQueue = []; 24 loadList.forEach(function(src) { 25 return loadQueue.push(createScript(src)); 26 }); 27 return loadQueue; 28 }; 29 return global.jsLoader = { 30 load: function(loadList) { 31 var queue; 32 queue = []; 33 queue = makeLoadQueue(loadList); 34 return insertScript(queue); 35 } 36 }; 37 })(window);
这个实例,展示了通过一个预制的清单文件 loadlist.js,来按照顺序同步加载script脚本文件
直接引用的方式:
<!-- jQuery 2.1.4 --> <script src="lib/admin-lte/plugins/jQuery/jQuery-2.1.4.min.js" type="text/javascript"></script> <!-- Bootstrap 3.3.2 JS --> <script src="lib/admin-lte/bootstrap/js/bootstrap.min.js" type="text/javascript"></script> <!-- iCheck --> <script src="lib/admin-lte/plugins/iCheck/icheck.min.js" type="text/javascript"></script> <!--angular--> <script src="lib/angular/angular.min.js"></script> <script src="lib/angular-ui-router/angular-ui-router.min.js"></script> <script src="lib/angular-animate/angular-animate.min.js"></script> <!--不带watchers的数据绑定指令--> <script src="//cdn.bootcss.com/angular-bindonce/0.3.1/bindonce.min.js"></script>
使用这个库的方式:
<script src="public/jsLoader/jsLoader.js"></script> <script src="loadList.js"></script>
loadList:
(function (global) { var loadList = [ 'lib/admin-lte/plugins/jQuery/jQuery-2.1.4.min', 'lib/admin-lte/bootstrap/js/bootstrap.min', 'lib/admin-lte/plugins/iCheck/icheck.min', 'lib/angular/angular.min', 'lib/angular-ui-router/angular-ui-router.min', 'lib/angular-animate/angular-animate.min', '//cdn.bootcss.com/angular-bindonce/0.3.1/bindonce.min', //main 'app' ] global.jsLoader.load(loadList); })(window);
对比html中的引入,改进了 代码的可读性和项目的可维护性了,并通过动态创建script,以非阻塞方式加载了js.
下一篇文章则改进这个库,使之能够同样的方式并行加载css