JS网页加载状态判断

网页加载状态一共分为5种,分别是:
 

//(未初始化)还没有调用send()方法
1.uninitialized:(Uninitialized) the send( ) method has not yet been invoked. 
 
//(载入)已调用send()方法,正在发送请求
2.loading:(Loading) the send( ) method has been invoked, request in progress. 
 
//(载入完成)send()方法执行完成,已经接收到全部响应内容
3.loaded:(Loaded) the send( ) method has completed, entire response received. 
 
//(交互)正在解析响应内容
4.interactive:(Interactive) the response is being parsed. 
 
//(完成)响应内容解析完成,可以在客户端调用了
5.completed:(Completed) the response has been parsed, is ready for harvesting.

1.html文件内的js代码判断

用document.onreadystatechange的方法来监听状态改变,然后用document.readyState == “complete”判断是否加载完成
代码如下:
 

//当页面加载状态改变的时候执行这个方法.
document.onreadystatechange = subSomething;
function subSomething(){
      //当页面加载状态
      if(document.readyState == “complete”) {
           //code
      }
}

2.打开F12控制台使用js脚本获取状态

爬虫爬网页时,有时页面一直在加载中,这时候如果要停止加载,则可以执行js脚本: window.stop();
 

//当页面一直在加载中(比如引用某个图片或脚本未完成),但所需内容已显示出来
if (document.readyState == 'interactive') {
	window.stop();
}

 

实例:实现网页正在加载时,提示正在加载,加载完成后隐藏提示信息

<!doctype html>
<html>
<head>
	<script src="../jquery.min.js"></script>
<meta charset="utf-8">
<title>加载状况提示</title>
	<style>
	
		#noticediv{
			display: none;
		}
	</style>
</head>

<body>
	
	<div id="noticediv">正在加载</div>
	<img src="https://xxx.xxx/images/test.jpg" />
	<script>
		
		//当页面加载状态改变的时候执行这个方法.
		document.onreadystatechange = subSomething;
	function subSomething(){
		console.info("监听中...........")
		console.info("状态:"+document.readyState);
      //当页面加载状态
      if(document.readyState=="interactive") {
           $("#noticediv").show();
		  console.info("加载中。。。。。。。")
      }
	if(document.readyState=="complete") {
           $("#noticediv").hide();
		console.info("加载完成。。。。。。。")
      }
}
	
	</script>
	
</body>
</html>

  • 2
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值