在firefox下,动态加载script标签和css标签,是可以简单地监听onload事件的,但在ie下,监听onload事件无效。为了解决这个问题,可以改用监听onreadystatechange,结合判断readyState的值是否等于loaded 或complete来判断是否onload。
YUI根据ie,webkit和其它做了三种情况区分。实际工作中,我们只用考虑ie和ff就差不多了,写了个简单的小demo,动态加载ie下的firebug组件:
=================================================
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>阿当制作</title>
</head>
<body>
<script type="text/javascript">
var s = document.createElement("script");
s.src = 'http://getfirebug.com/releases/lite/1.2/firebug-lite-compressed.js';
s.type="text/javascript";
if(document.all){
s.onreadystatechange = function(){
if(this.readyState == "loaded" || this.readyState == "complete"){
alert("loaded success in ie");
}
}
} else {
s.onload = function(){
alert("load success");
}
}
document.body.appendChild(s);
</script>
</body>
</html>