如何在页面加载完成之后添加jQuery

在页面加载完成之后可能在某种特殊的情况下需要添加jQuery.那么请注意onreadystatechange和onload这俩个方法.
代码:

<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>
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值