-
一般现代浏览器通过侦听事件获得脚本加载完成时的状态
var script = document.createElement('script');
script.type = 'text/javascript';
//Firefox, Chrome
script.onload = function(){
alert('script loaded!');
};
script.src = 'http://code.jquery.com/jquery-1.4.2.min.js';
document.getElementsByTagName('head')[0].appendChild(script); -
ie支持另外一种方式,会触发readystatechange事件
loading:开始下载
complete:所有数据已准备就绪
var script = document.createElement('script');
script.type = 'text/javascript';
//IE
script.onreadystatechange = function(){
if(script.readyState == 'loaded' || script.readyState == 'complete'){
script.onreadystatechange = null;
alert('Script loaded');
}
}
script.src = 'http://code.jquery.com/jquery-1.4.2.min.js';
document.getElementsByTagName('head')[0].appendChild(script); -
兼容方法
/**
* 载入脚本
* @param {String} url 载入的地址
* @param {Function} callback 载入后需执行的函数
*/
function loadScript(url, callback){
var script = document.createElement('script');
script.type = 'text/javascript';
//IE
if(script.readyState){
script.onreadystatechange = function(){
if(script.readyState == 'loaded' || script.readyState == 'complete'){
script.onreadystatechange = null;
callback();
}
}
} else { //非IE
script.onload = function(){
callback();
}
}
script.src = null;
document.getElementsByTagName('head')[0].appendChild(script);
}
//example
loadScript('http://code.jquery.com/jquery-1.4.2.min.js', function(){
alert('File is loaded!');
}) -
XMLRequest脚本注入
var xhr = new XMLHttpRequest();
xhr.open('get', 'http://code.jquery.com/jquery-1.4.2.min.js', true);
xhr.onreadystatechange = function(){
if(xhr.readySate == 4){
if(xhr.status >= 200 && shr.status < 300 || xhr.status == 304){ //200 有效响应; 304 从缓存读取
var script = document.createElement('script');
script.type = 'text/javascript';
script.text = xhr.responseText;
document.body.appendChild(script);
}
}
};
xhr.send(null);