在页面加载完成之后可能在某种特殊的情况下需要添加jQuery.那么请注意onreadystatechange和onload这俩个方法.
代码:
chrome/ff会在script加载完毕后调用onload()方法.
IE6-8会在script.readyState='loaded'或script.readyState == 'complete'的时候调用onreadystatechange()方法.
在某些情况我们不清楚当前的document是否已经加载完毕,如果还没有加载完毕的话,我们就需要修改一下上面的代码
代码:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script language="javascript">
var test=function(){
var script = document.createElement( 'script' );
script.type = 'text/javascript';
script.src = "http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js";
script.onload=script.onreadystatechange=function(){
/*
*用"!script.readyState"判断浏览器是否支持onload方法,
*如果"!script.readyState=false"者说明浏览器是IE,
*接下来只需判断script.readState属性是否是'loaded'或'complete',
*这俩个属性都说明js已经加载完毕.
*/
if(!script.readyState||script.readyState == 'loaded'||script.readyState == 'complete'){
jQuery(function(){
alert($('div').html());
});
}
};
//在head中添加script标签
document.documentElement.firstChild.appendChild(script);
};
</script>
</head>
<body onload="test()">
<div>我是测试代码!</div>
</body>
</html>
chrome/ff会在script加载完毕后调用onload()方法.
IE6-8会在script.readyState='loaded'或script.readyState == 'complete'的时候调用onreadystatechange()方法.
在某些情况我们不清楚当前的document是否已经加载完毕,如果还没有加载完毕的话,我们就需要修改一下上面的代码
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script language="javascript">
//判断当前document是否已经加载完毕
if (document.body && (!document.readyState || document.readyState == 'complete') ){
//因为情况所限,if里的代码不会执行.
var script = document.createElement( 'script' );
script.type = 'text/javascript';
script.src = "http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js";
script.onload=script.onreadystatechange=function(){
/*
*用"!script.readyState"判断浏览器是否支持onload方法,
*如果"!script.readyState=false"者说明浏览器是IE,
*接下来只需判断script.readState属性是否是'loaded'或'complete',
*这俩个属性都说明js已经加载完毕.
*/
if(!script.readyState||script.readyState == 'loaded'||script.readyState == 'complete'){
alert($('div').html());
}
};
//在head中添加script标签
document.documentElement.firstChild.appendChild(script);
}else{
document.write( '<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js" type="text/javascript"><\/script>' );
window.onload=function(){
alert($('div').html()+"!!!");
};
}
</script>
</head>
<body>
<div>我是测试代码!</div>
</body>
</html>