function loadJS(url, success) { var domScript = document.createElement('script'); domScript.src = url; success = success || function () {}; domScript.onload = domScript.onreadystatechange = function () { if (!this.readyState || 'loaded' === this.readyState || 'complete' === this.readyState) { success(); this.onload = this.onreadystatechange = null; this.parentNode.removeChild(this); } } document.getElementsByTagName('head')[0].appendChild(domScript); } loadJS("1.js"); </script>
转自 http://yijiebuyi.com/blog/2b23b571a0d5c94047f7e9c3150ac25d.html
!function loadJS(){ var jsFile = [ {name:'file1',path:'js/file1.js',active:false,load:false}, {name:'file2',path:'js/file2.js',active:false,load:false}, {name:'file3',path:'js/file3.js',active:false,load:false}, {name:'file4',path:'js/file4.js',active:false,load:false}, {name:'file5',path:'js/file5.js',active:false,load:false} ] jsFile.forEach(function(item, index){ if(localStorage['file_' + item.name]){ item.load = true implementJS(item, index) }else{ $.ajax({ type:"get", url:item.path, dataType:'text', success:function(data){ item.content = data item.load = true implementJS(item, index) } }); } }) function implementJS(item, index){ //如果上一个文件已经执行了,则执行这个js文件 if(index == 0 || jsFile[index - 1].active){ storageJS(item, index) //尝试执行下一个js文件 jsFile[index + 1] && jsFile[index + 1].load && implementJS(jsFile[index + 1], index + 1) } } function storageJS(item, index){ //存储并执行js文件 var name = 'file_' + item.name localStorage[name] = item.content || localStorage[name] || '' //这里要使用window.eval或者eval.call(window),否则eval里面的变量就不是全局变量 window.eval(localStorage[name]) item.active = true } }()