仿AJAX的动态加载数据的JS函数,支持回调函数。
function loadjs(url,callback){ var head = document.getElementsByTagName("head")[0]; var script = document.createElement('script'); script.onload = script.onreadystatechange = script.onerror = function (){ if (script && script.readyState && /^(?!(?:loaded|complete)$)/.test(script.readyState)) return; script.onload = script.onreadystatechange = script.onerror = null; script.src = ''; script.parentNode.removeChild(script); script = null; callback(); } script.src = url; try { head.appendChild(script); } catch (exp) {}}
基本用法:
loadjs("ajax.php?return=value",function(){alert(value);});
只需要在ajax.php里面输出类似:var value="this is value.";的结果即可,即通过ajax.php来给一个JavaScript变量赋值。在loadjs的第二个参数里面传一个回调函数,这个回调函数可以调ajax.php里面返回的数据。
更多JS函数请看
loadmultijs函数是对loadjs的改装,它可以加载多个JS文件,支持回调函数。当多个JS文件全部加载完毕后再执行回调函数。
function loadjs(url,callback){ var head = document.getElementsByTagName("head")[0]; var script = document.createElement('script'); script.onload = script.onreadystatechange = script.onerror = function (){ if (script && script.readyState && /^(?!(?:loaded|complete)$)/.test(script.readyState)) return; script.onload = script.onreadystatechange = script.onerror = null; script.src = ''; script.parentNode.removeChild(script); script = null; callback(); } script.charset = "gb2312"; script.src = url; try { head.appendChild(script); } catch (exp) {}}function loadmultijs(url,callback){ if(Object.prototype.toString.call(url)==='[object Array]'){ //是否数组 this.suc = 0; //加载计数 this.len = url.length; //数组长度 var a = this; for(var i = 0;i < url.length;i++){ loadjs(url[i],function(){ a.suc++; if(a.suc == a.len) try{callback();}catch(e){} }); } }else if(typeof(url) == 'string'){ loadjs(url,callback); }}使用方法:
var url = [ 'ajax.php?ajax=1', 'functions.js' ];loadmultijs(url,function(){ alert("加载完毕。"); /* 这里可以调用动态加载的JS文件的数据或方法 */ });