---
title: "Tools"
author: "vianoz"
date: "2011-11-20T22:23:41Z"
tags: []
categories: ["非技术"]
slug: "tools"
draft: false
lastmod: "2012-10-24T11:45:02Z"
id: 1269726
url: "https://vianoz.iteye.com/blog/1269726"
---

.一、背景  
假设有一个图片浏览的网页，每日pv量大概在80,000,000左右，uv量在3,000,000左右，现需要统计每张图片的pv量。  
二、方案  
方案1 每浏览一张图片，发送图片id和浏览数量到后台，并记录到数据库（可能会涉及到缓存机制，比如Memcache）  
方案2 在页面中用js记录用户访问每张图片的次数，在用户关闭网页或刷新页面时，发送图片id和浏览数量到后台，并记录到数据库（可能会涉及到缓存机制，比如Memcache）  
分析：  
方案1中，需要发送大概80,000,000次（pv量）数据到后台，而方案2中只需要发送3,000,000次（uv量）数据，降低了1个数量级，这大大减轻了接入层机器的负载  
三、实现  
采用方案2。需要根据用户的关闭网页行为做js事件触发，此处我们用到onbeforeunload事件。

代码如下：

**\[javascript]** [view plain](http://vianoz.iteye.com/admin/blogs/1269726/ "view plain")[copy](http://vianoz.iteye.com/admin/blogs/1269726/ "copy")[print](http://vianoz.iteye.com/admin/blogs/1269726/ "print")[?](http://vianoz.iteye.com/admin/blogs/1269726/ "?")

01. &lt;script&gt;
02. var g\_img\_pv = {};  //用于记录图片id和点击次数
03. function Fempty(v){
04. if(v!=null && (typeof(v)=='object' || typeof(v)=='function')) return false;
05. return ((""==v || undefined==v || null==v)?true:false);
06. }
07. function FaddEvent(e,evt,fn,isID)
08. {
09. if(isID==true) e=Fid(e);
10. if(!Fempty(e.attachEvent) && (typeof(e.attachEvent)=="function" || typeof(e.attachEvent)=="object"))
11. e.attachEvent("on"+evt,fn);
12. else if(!Fempty(e.addEventListener) && (typeof(e.addEventListener)=="function" || typeof(e.addEventListener)=="object"))
13. e.addEventListener(evt,fn,false);
14. }
15. function stat\_img\_pv()
16. {
17. if(!g\_img\_pv)
18. {
19. return;
20. }
21. var ids = '', counts = '';
22. for(var picid in g\_img\_pv)
23. {
24. if(parseInt(picid) == picid)
25. {
26. ids += picid + ',';
27. counts += g\_img\_pv\[picid] + ',';
28. }
29. }
30. ids = ids.substring(0, ids.length-1);
31. counts = counts.substring(0, counts.length-1);
32. var url = 'http://www.example.com/statimgpv.php?'+ids+'&counts='+counts+'&t='+Math.random();
33. var img = new Image();
34. img.src = url;
35. setTimeout(function(){},1000);
36. }
37. FaddEvent(window, 'beforeunload', stat\_img\_pv, false);
38. &lt;/script&gt;

```
<script>
var g_img_pv = {};	//用于记录图片id和点击次数

function Fempty(v){
	if(v!=null && (typeof(v)=='object' || typeof(v)=='function')) return false;
	return ((""==v || undefined==v || null==v)?true:false);
}
function FaddEvent(e,evt,fn,isID)
{
	if(isID==true) e=Fid(e);
	if(!Fempty(e.attachEvent) && (typeof(e.attachEvent)=="function" || typeof(e.attachEvent)=="object"))
		e.attachEvent("on"+evt,fn);
	else if(!Fempty(e.addEventListener) && (typeof(e.addEventListener)=="function" || typeof(e.addEventListener)=="object"))
		e.addEventListener(evt,fn,false);
}
function stat_img_pv()
{
	if(!g_img_pv)
	{
		return;
	}
	var ids = '', counts = '';
	for(var picid in g_img_pv)
	{
		if(parseInt(picid) == picid)
		{
			ids += picid + ',';
			counts += g_img_pv[picid] + ',';
		}
	}
	ids = ids.substring(0, ids.length-1);
	counts = counts.substring(0, counts.length-1);

	var url = 'http://www.example.com/statimgpv.php?'+ids+'&counts='+counts+'&t='+Math.random();
	var img = new Image();
	img.src = url;
	setTimeout(function(){},1000);
}
FaddEvent(window, 'beforeunload', stat_img_pv, false);
</script>
```

写到这里好像是完成了，运行一下试试，用httpwatch抓一下包看看http请求是否成功。悲剧，在ie和firefox下，http请求被aborted了，截图如下：

![](http://hi.csdn.net/attachment/201107/13/0_1310539764s22U.gif)

这是怎么回事呢？个人认为，在设置完img变量的src属性后，并没有立即触发http请求，这样，当onbeforeunload响应完成，然后是响应onunload，接着页面就关闭了，这就导致了我们的img.src还没有被触发。  
怎么办呢？第一个反应是在设置完img变量的src属性后，sleep一会，从而等待http请求被触发。但是js里貌似没有sleep函数，怎么办？  
一种笨方法：  
在img.src = url;后，加一个长时间的操作，比如加一个for循环，这样不就达到了延迟的目的了吗？试一下，firefox下ok，ie下，不好使…… 万恶的ie啊！

下面给出一种解决办法（在ie和firefox下测试均ok）：

 

 

**\[javascript]** [view plain](http://vianoz.iteye.com/admin/blogs/1269726/ "view plain")[copy](http://vianoz.iteye.com/admin/blogs/1269726/ "copy")[print](http://vianoz.iteye.com/admin/blogs/1269726/ "print")[?](http://vianoz.iteye.com/admin/blogs/1269726/ "?")

1. function stat\_img\_pv()
2. {
3. ……
4. var img = new Image();
5. img.src = url;
6. setTimeout(function(){},1000);  //就是加入这一行！
7. }

```
function stat_img_pv()
{
	……
	var img = new Image();
	img.src = url;
	setTimeout(function(){},1000);	//就是加入这一行！
}
```

但是为啥好使我就不知道了，很偶然的尝试下发现ok。等待大牛的解答！

附  
onbeforeunload与onunload事件  
onunload，onbeforeunload都是在刷新或关闭时调用，可以在&lt;script&gt;脚本中通过 window.onunload来指定或者在&lt;body&gt;里指定。区别在于onbeforeunload在onunload之前执行，它还可以阻止onunload的执行。  
onbeforeunload也是在页面刷新或关闭时调用，onbeforeunload是正要去服务器读取新的页面时调用，此时还没开始读取；而onunload则已经从服务器上读到了需要加载的新的页面，在即将替换掉当前页面时调用。onunload是无法阻止页面的更新和关闭的。而onbeforeunload可以做到。  
1、onbeforeunload事件：  
说明：目前三大主流浏览器中firefox和IE都支持onbeforeunload事件,opera尚未支持。  
用法：  
·object.onbeforeunload = handler  
·&lt;element onbeforeunload = "handler" … &gt;&lt;/element&gt;  
描述：  
事件触发的时候弹出一个有确定和取消的对话框，确定则离开页面，取消则继续待在本页。handler可以设一个返回值作为该对话框的显示文本。  
　　触发于：  
　　·关闭浏览器窗口  
　　·通过地址栏或收藏夹前往其他页面的时候  
　　·点击返回，前进，刷新，主页其中一个的时候  
　　·点击 一个前往其他页面的url连接的时候  
　　·调用以下任意一个事件的时候：click，document write，document open，document close，window close ，window navigate ，window NavigateAndFind,location replace,location reload,form submit.  
　　·当用window open打开一个页面，并把本页的window的名字传给要打开的页面的时候。  
　　·重新赋予location.href的值的时候。  
　　·通过input type=”submit”按钮提交一个具有指定action的表单的时候。  
　　可以用在以下元素：  
　　·BODY, FRAMESET, window  
　　平台支持：  
　　IE4+/Win, Mozilla 1.7a+, Netscape 7.2+, Firefox0.9+  
示例：

**\[javascript]** [view plain](http://vianoz.iteye.com/admin/blogs/1269726/ "view plain")[copy](http://vianoz.iteye.com/admin/blogs/1269726/ "copy")[print](http://vianoz.iteye.com/admin/blogs/1269726/ "print")[?](http://vianoz.iteye.com/admin/blogs/1269726/ "?")

01. &lt;html xmlns="http://www.w3.org/1999/xhtml"&gt;
02. &lt;head&gt;
03. &lt;meta http-equiv="Content-Type" content="text/html; charset=gb2312" /&gt;
04. &lt;title&gt;onbeforeunload测试&lt;/title&gt;
05. &lt;script&gt;
06. function checkLeave(){
07. event.returnValue="确定离开当前页面吗？";
08. }
09. &lt;/script&gt;
10. &lt;/head&gt;
11. &lt;body onbeforeunload="checkLeave()"&gt;
12. &lt;/body&gt;
13. &lt;/html&gt;

```
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>onbeforeunload测试</title>
<script>
function checkLeave(){
     　event.returnValue="确定离开当前页面吗？";
}
</script>
</head>
<body onbeforeunload="checkLeave()">
</body>
</html>
```

但是onbeforeunload有个小毛病，就是页面刷新时，他还是会调用到onbeforeunload，为什么？其实刷新就相当于关闭了这个IE再重新打开的意思，因此还是会调用到onbeforeunload。  
究竟怎么解决刷新不调用onbeforeunload呢？网上提供很多方法，本人觉得最实用还是以下这段JS

 

 

**\[javascript]** [view plain](http://vianoz.iteye.com/admin/blogs/1269726/ "view plain")[copy](http://vianoz.iteye.com/admin/blogs/1269726/ "copy")[print](http://vianoz.iteye.com/admin/blogs/1269726/ "print")[?](http://vianoz.iteye.com/admin/blogs/1269726/ "?")

01. window.onbeforeunload = function(){
02. var n = window.event.screenX - window.screenLeft;
03. var b = n &gt; document.documentElement.scrollWidth-20;
04. if(b && window.event.clientY&lt;0 || window.event.altKey)
05. {
06. alert("是关闭而非刷新");
07. window.event.returnValue = "是否关闭？";
08. }else{
09. alert("是刷新而非关闭");
10. }
11. }

```
window.onbeforeunload = function(){   
      var n = window.event.screenX - window.screenLeft;   
      var b = n > document.documentElement.scrollWidth-20;   
      if(b && window.event.clientY<0 || window.event.altKey)   
      {   
          alert("是关闭而非刷新");   
          window.event.returnValue = "是否关闭？";
      }else{
          alert("是刷新而非关闭");   
      }   
}
```

2、onunload事件  
用法：  
·object.onunload = handler  
·&lt;element onunload = "handler"&gt;&lt;/element&gt;  
描述：  
当用户关闭一个页面时触发 onunload 事件。  
　　触发于：  
　　·关闭浏览器窗口  
　　·通过地址栏或收藏夹前往其他页面的时候  
　　·点击返回，前进，刷新，主页其中一个的时候  
　　·点击一个前往其他页面的url连接的时候  
　　·调用以下任意一个事件的时候：click，document write，document open，document close，window close ，window navigate ，window NavigateAndFind,location replace,location reload,form submit.  
　　·当用window open打开一个页面，并把本页的window的名字传给要打开的页面的时候。  
　　·重新赋予location.href的值的时候。  
　　·通过input type=”submit”按钮提交一个具有指定action的表单的时候。  
示例：

 

 

**\[javascript]** [view plain](http://vianoz.iteye.com/admin/blogs/1269726/ "view plain")[copy](http://vianoz.iteye.com/admin/blogs/1269726/ "copy")[print](http://vianoz.iteye.com/admin/blogs/1269726/ "print")[?](http://vianoz.iteye.com/admin/blogs/1269726/ "?")

01. &lt;html xmlns="http://www.w3.org/1999/xhtml"&gt;
02. &lt;head&gt;
03. &lt;meta http-equiv="Content-Type" content="text/html; charset=gb2312" /&gt;
04. &lt;title&gt;onunload测试&lt;/title&gt;
05. &lt;script&gt;
06. function checkLeave(){
07. alert("欢迎下次再来！");
08. }
09. &lt;/script&gt;
10. &lt;/head&gt;
11. &lt;body onunload="checkLeave()"&gt;
12. &lt;/body&gt;
13. &lt;/html&gt;