旧系统网页性能收集,兼容IE5,低侵入收集网页脚本

开发背景

  • 短时间内完成网页性能统计上传,考虑到企业内实际环境,很多网页/系统需要运行在IE 5 兼容模式下,开发一个脚本,在不影响原网页的情况下,收集相应 用户电脑 打开网页的性能指标。

收集要素

  • 进入页面时间,加载Js时间
  • 页面所有元素加载完成时间
  • 因为在原网页将该脚本放到最前面,故两者时间差为用户实际等待页面Ready时间(白屏),实际体验可能与渲染引擎相关(现代浏览器 大大快于IE,故该指标可作参考)
  • IE 打开页面默认弹窗,会影响结束时间,会以用户点击弹窗作为结束
  • 浏览器信息等可自行拓展

# 使用方法
- 引入代码文件,并给特定`id`, 相应标签属性可追加自定义值,用于辅助统计
- 涉及js 回调,所以需要提前赋值


# 技术特点
- 浏览器兼容(主要是IE 5、低侵入)
- 无三方库,考虑方便快速拓展

(function () {

Date.prototype.pattern = function (fmt) {
	var o = {
		"M+": this.getMonth() + 1, //月份         
		"d+": this.getDate(), //日         
		"h+": this.getHours() % 12 == 0 ? 12 : this.getHours() % 12, //小时         
		"H+": this.getHours(), //小时         
		"m+": this.getMinutes(), //分         
		"s+": this.getSeconds(), //秒         
		"q+": Math.floor((this.getMonth() + 3) / 3), //季度         
		"S": this.getMilliseconds() //毫秒         
	};
	var week = {
		"0": "/u65e5",
		"1": "/u4e00",
		"2": "/u4e8c",
		"3": "/u4e09",
		"4": "/u56db",
		"5": "/u4e94",
		"6": "/u516d"
	};
	if (/(y+)/.test(fmt)) {
		fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
	}
	if (/(E+)/.test(fmt)) {
		fmt = fmt.replace(RegExp.$1, ((RegExp.$1.length > 1) ? (RegExp.$1.length > 2 ? "/u661f/u671f" : "/u5468") : "") + week[this.getDay() + ""]);
	}
	for (var k in o) {
		if (new RegExp("(" + k + ")").test(fmt)) {
			fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
		}
	}
	return fmt;
}

function getJsScriptDataScript() {
	var data = document.getElementById('statisticalScriptId').getAttribute('data');
	var key = 'code';
	if (data) {
		var result = data.match(new RegExp(key + "=[^\?\&]+", "g"));
		var value = result ? result[0].split('=')[1] : '';
		return value;
	}

	return '';
}

function getJsScriptRemark() {
	return document.getElementById('statisticalScriptId').src;
}

//兼容bind函数
if (!Function.prototype.bind) {
	Function.prototype.bind = function () {
		if (typeof this !== 'function') {
			throw new TypeError('Function.prototype.bind - what is trying to be bound is not callable');
		}
		var _this = this;
		var obj = arguments[0];
		var ags = Array.prototype.slice.call(arguments, 1);
		return function () {
			_this.apply(obj, ags);
		};
	};
}

//兼容addEventListener函数
function addEventListener(ele, event, fn) {
	if (ele.addEventListener) {
		ele.addEventListener(event, fn, false);
	} else {
		ele.attachEvent('on' + event, fn.bind(ele));
	}
}

//兼容removeEventListener函数
function removeEventListener(ele, event, fn) {
	if (ele.removeEventListener) {
		ele.removeEventListener(event, fn, false);
	} else {
		ele.detachEvent('on' + event, fn.bind(ele));
	}
}

//闭包自治性
var ClientInfo = {
	InJsTime: '',
	InteractiveTime: '',
	DOMContentLoadedTime:'',
	LoadTime: '',
	ComputeName: '',
	UserName: '',
	IdentifyCode: getJsScriptDataScript(),
	Remark: getJsScriptRemark(),

	Href: '',
	Origin: '',
	Host: '',
	Port: '',
	PathName:''
};
ClientInfo.InJsTime = getNowDateTime();

try {
    var WshShell = new ActiveXObject("WScript.Shell");
    //document.write("计算机名 = " + WshShell.ExpandEnvironmentStrings("%COMPUTERNAME%") + "<br/>");
    //document.write("登录用户名 = " + WshShell.ExpandEnvironmentStrings("%USERNAME%") + "<br/>");
    ClientInfo.ComputeName = WshShell.ExpandEnvironmentStrings("%COMPUTERNAME%");
    ClientInfo.UserName = WshShell.ExpandEnvironmentStrings("%USERNAME%");

} catch (e) {

}

addEventListener(window, 'load', function () {
	//console.log('window load ' + (new Date()).pattern("yyyy-MM-dd hh:mm:ss S"));
	ClientInfo.LoadTime = getNowDateTime();
	sendData();
});

addEventListener(document, 'readystatechange', function () {
	var state = document.readyState;
	if (state == 'interactive') {
		ClientInfo.InteractiveTime = getNowDateTime();
		//console.log('document ' + document.readyState + (new Date()).pattern("yyyy-MM-dd hh:mm:ss S"));
	}
});

addEventListener(document, 'DOMContentLoaded', function () {
	ClientInfo.DOMContentLoadedTime = getNowDateTime();
	//console.log('document DOMContentLoaded' + (new Date()).pattern("yyyy-MM-dd hh:mm:ss S"));
});

function getNowDateTime() {
	var timeOffSet = (new Date()).getTimezoneOffset();

	return (new Date()).getTime() - timeOffSet * 60 * 1000; //(new Date()).pattern("yyyy-MM-dd hh:mm:ss S");
}

function sendData() {
	ClientInfo.Href = window.location.href;
	ClientInfo.Origin = window.location.origin;
	ClientInfo.Host = (window.location.host).toLowerCase().replace(/.chn.nexchip/, "");
	ClientInfo.Port = window.location.port;
	ClientInfo.PathName = window.location.pathname;

	var hostArray = 'xxxt01,xxxs01,xxxs02';
	var url = '';
	if (borGHostArray.indexOf(ClientInfo.Host) > -1) {
		url = window.location.protocol + "//" + window.location.host + "/bridgeapi/Api/BridgePageRecord/PostData"
	} else {
		url = 'http://xxxs01x/msgcenterapi/Api/SeriPageLoadRecord/PostData';
    }

	var paramObj = {
		httpUrl:url,
		type: 'post',
		data: ClientInfo			
	}

	/*请求调用*/
	httpRequest(paramObj, function (respondDada) {
		//这里编写成功的回调函数
		//console.log(respondDada)
	}, function () {
		//console.log('网络错误');
	});
}

function httpRequest(paramObj, fun, errFun) {
	var xmlhttp = null;
	/*创建XMLHttpRequest对象,
	 *老版本的 Internet Explorer(IE5 和 IE6)使用 ActiveX 对象:new ActiveXObject("Microsoft.XMLHTTP")
	 * */
	if (window.XMLHttpRequest) {
		xmlhttp = new XMLHttpRequest();
	} else if (window.ActiveXObject) {
		xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
	}
	/*判断是否支持请求*/
	if (xmlhttp == null) {
		alert('你的浏览器不支持XMLHttp');
		return;
	}
	/*请求方式,并且转换为大写*/
	var httpType = (paramObj.type || 'GET').toUpperCase();
	/*数据类型*/
	var dataType = paramObj.dataType || 'json';
	/*请求接口*/
	var httpUrl = paramObj.httpUrl || '';
	/*是否异步请求*/
	var async = paramObj.async || true;
	/*请求参数--post请求参数格式为:foo=bar&lorem=ipsum*/
	var paramData = paramObj.data || [];
	var requestData = '';
	for (var name in paramData) {
		requestData += name + '=' + paramData[name] + '&';
	}
	requestData = requestData == '' ? '' : requestData.substring(0, requestData.length - 1);
	//console.log(requestData)

	/*请求接收*/
	xmlhttp.onreadystatechange = function () {
		if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
			/*成功回调函数*/
			fun(xmlhttp.responseText);
		} else {
			/*失败回调函数*/
			errFun;
		}
	}

	/*接口连接,先判断连接类型是post还是get*/
	if (httpType == 'GET') {
		xmlhttp.open("GET", httpUrl, async);
		xmlhttp.send(null);
	} else if (httpType == 'POST') {
		xmlhttp.open("POST", httpUrl, async);
		//发送合适的请求头信息
		xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
		xmlhttp.send(requestData);
	}
}

	//setTimeout(function () { alert('表单打开超过20分钟,请先暂存或刷新,否则可能会丢失数据') }, 1000 * 60 * 20);

})();

热门相关:恭喜你被逮捕了   大奶导师和李大日2   自由夫人   D罩杯私人助理   本法官萌萌哒