首页 > 代码库 > loadjs异步加载javascript回调
loadjs异步加载javascript回调
function loadjs(url,callback){
var script=document.createElement(‘script‘);
script.type="text/javascript";
script.src=http://www.mamicode.com/url;
if(script.onreadystatechange){
script.onreadystatechange=function(){
if(script.readyState=‘loaded‘||script.readyState=‘complate‘){
callback();//script is loaded;
}
}
}else{
script.onloaded=function(){
callback();//script is loaded;
}
}
document.getElementsByTagName(‘head‘)[0].appendChild(script);
}
function callback(){
alert("script is loaded");
}
//window.onload之后才去加载的js,这样拆分js的加载有利于首页加载速度提高用户体验
window.onload=function(){
loadjs("jquery.js",callback);
loadjs("test.js",callback);
}
loadjs异步加载javascript回调