js页面测速
前台页面:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>页面速度</title> <script src="jquery-1.4.4.js"></script> <script> var obj = {}; </script> </head> <body> <script> <!--记录时间点--> obj.one = new Date*1+10; obj.two = new Date*1+50; obj.three = new Date*1+60; obj.four = new Date*1+80; obj.five = new Date*1+100; var str = $.param(obj); var img = new Image(); img.src = 'ns.php?'+str; //加载完成或失败都要绑定,如果页面没有正确输出图片(只有头信息是不行的)则会触发onerror事件 img.onload = img.onerror = function() { //清除无用资源 obj = img = null; }; console.log(img); //追加显示图片,故我们要把图片变量也清除掉 /*$(function(){ $("#btn").click(function(){ $(document.body).append(img); //document.body.appendChild(img); }) })*/ </script> <button id="btn">单击显示图片</button> </body> </html>
后台页面ns.php
<?php header("Content-Type: image/jpg"); sleep(1); //如果不输出则会执行onerror事件 // echo file_get_contents('a.jpg'); $rs = $_GET; //和前一个时间点计算差值 $val_arr = array_values($rs); $len = count($val_arr); $diff_arr = array(); for($i=0;$i<$len;$i++) { $diff_arr[] = $i==0 ? 0 : $val_arr[$i]-$val_arr[$i-1]; } $count = 0; $unit = 10;//根据具体情况在调整 foreach($rs as $k=>$v){ $rs[$k] = array( 'stamp' =>$v, 'differ'=>$diff_arr[$count++], //注意%不支持大数求余 'chart' =>str_pad('', fmod($v, $unit), '*'), ); } my_log($rs); function my_log($msg = '', $log_name = 'song') { define('APP_PATH', 'E:\wamp\www\test'); $date = date('Y-m-d H:i:s').' --> '; $msg = var_export($msg,true); $msg = $date.$msg."\n"; $filepath = APP_PATH.DIRECTORY_SEPARATOR.$log_name.'_'.date('Y-m-d').'.txt'; if ( ! $fp = fopen($filepath, 'ab')) { echo 'error'; return FALSE; } flock($fp, LOCK_EX); fwrite($fp, $msg); flock($fp, LOCK_UN); fclose($fp); chmod($filepath, 0777); }
记录页面中每个图片的加载时间(只提供前台页面后台自行处理):
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>无标题文档</title> <script type="text/javascript" src="jquery-1.4.4.js"></script> </head> <body> <img src="ns.php" width="100px" name="img1" /> <img src="ns.php" width="100px" name="img2" /> <img src="ns.php" width="100px" name="img3" /> <img src="ns.php" width="100px" name="img4" /> <script> $(function(){ var len = $("img").length; var counter = 0; var imgObj = {}; //处理函数 var dealstr = function(){ counter++; var key = $(this).attr('name'); //注意这里不能用.key的语法,否则会把key字符串当做键名 imgObj[key] = new Date()*1; } //绑定事件 $("img").error(dealstr); $("img").load(dealstr); //如果所有图片都加载完以后向后端发送统计数据 var timer = setInterval(function(){ if(counter == len){ $.get('ns.php',imgObj,function(data){ alert(data); }) clearInterval(timer); } document.title = counter; },100) }) </script> </body> </html>