用js 实现requirejs的效果
做的一个练习中,引入的js文件有八十个而且之间有依赖关系--用require用的不顺手==出了很多问题,然后酱紫。。。
1 将requirejs的path另写一个JSOn文件 config.json;
[ "js/libs/jquery/jquery-2.1.1.js", "js/libs/jquery/jquery-ui-1.10.3.min.js", "js/libs/bootstrap/bootstrap.min.js", "js/smartadmin/notification/SmartNotification.min.js", "js/smartadmin/smartwidgets/jarvis.widget.min.js", "js/plugin/sparkline/jquery.sparkline.min.js", "js/plugin/jquery-validate/jquery.validate.min.js", "js/plugin/masked-input/jquery.maskedinput.min.js", "js/plugin/select2/select2.min.js", "js/plugin/bootstrap-slider/bootstrap-slider.min.js", "js/plugin/msie-fix/jquery.mb.browser.min.js", "js/plugin/fastclick/fastclick.min.js" ..... ]
2 config.js
//获取JSOn数据
function getCode(url,fn){ var xhr = new XMLHttpRequest(); xhr.open("GET", url); xhr.setRequestHeader("content-type", "application/json"); xhr.onreadystatechange = function() { if (xhr.readyState == 4) { var text = xhr.responseText; console.log(typeof(text)); var obj=JSON.parse(text); fn&&fn(obj); } } xhr.send(); } //将js插入到html var load_Script=function(A,n){ var L=A.length; var path=A[n]; console.log("path="+path) var script=document.createElement("script"); script.type = "text/javascript"; script.setAttribute("src",path); script.setAttribute("defer","defer"); script.onload=function(){ //解决加载依赖性 if(n<L-1){ load_Script(A,n+1); } } document.body.appendChild(script); } getCode("./config.json",function(obj){ console.log(obj.length); load_Script(obj,0); });