fe-calc-wpo.js 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  1. /**
  2. * 计算并保存网页加载时间
  3. * @author zhaoxianlie
  4. */
  5. baidu.calcPageLoadTime = (function(){
  6. var wpoInfo = {};
  7. /**
  8. * 获取页面的http header
  9. * @return {[type]}
  10. */
  11. var getHttpHeaders = function(){
  12. if(wpoInfo.header && wpoInfo.time && wpoInfo.pageInfo) {
  13. sendWpoInfo();
  14. }else{
  15. $.ajax({
  16. type: 'GET',
  17. url : window.location.href,
  18. complete: function( xhr,data ){
  19. wpoInfo.header = {
  20. "date" : xhr.getResponseHeader('Date'),
  21. "connection" : xhr.getResponseHeader('Connection'),
  22. "contentEncoding" : xhr.getResponseHeader('Content-Encoding'),
  23. "contentLength" : xhr.getResponseHeader('Content-Length'),
  24. "server" : xhr.getResponseHeader('Server'),
  25. "vary" : xhr.getResponseHeader('Vary'),
  26. "transferEncoding" : xhr.getResponseHeader('Transfer-Encoding'),
  27. "contentType" : xhr.getResponseHeader('Content-Type'),
  28. "cacheControl" : xhr.getResponseHeader('Cache-Control'),
  29. "exprires" : xhr.getResponseHeader('Exprires'),
  30. "lastModified" : xhr.getResponseHeader('Last-Modified')
  31. };
  32. getPageInfo();
  33. getPageLoadTime();
  34. sendWpoInfo();
  35. }
  36. });
  37. }
  38. };
  39. /**
  40. * 页面相关信息
  41. */
  42. var getPageInfo = function(){
  43. wpoInfo.pageInfo = {
  44. title : document.title,
  45. url : location.href
  46. };
  47. };
  48. /**
  49. * 获取网页的加载时间
  50. */
  51. var getPageLoadTime = function(){
  52. wpoInfo.time = performance.timing;
  53. };
  54. /**
  55. * 发送wpo数据
  56. * @return {[type]}
  57. */
  58. var sendWpoInfo = function(){
  59. chrome.extension.sendMessage({
  60. type : MSG_TYPE.CALC_PAGE_LOAD_TIME,
  61. wpo : wpoInfo
  62. });
  63. };
  64. /**
  65. * 提取wpo信息
  66. */
  67. var getWpoInfo = function(){
  68. // 如果是网络地址,才去获取header
  69. if(/^((http)|(https))\:\/\//.test(location.href)) {
  70. getHttpHeaders();
  71. }
  72. // 否则只提取performance信息
  73. else{
  74. getPageInfo();
  75. getPageLoadTime();
  76. sendWpoInfo();
  77. }
  78. };
  79. var init = function(){
  80. chrome.runtime.onMessage.addListener(function(request,sender,callback){
  81. // 获取页面相关性能数据
  82. if(request.type == MSG_TYPE.GET_PAGE_WPO_INFO) {
  83. (function check() {
  84. (document.readyState == "complete") ? getWpoInfo() : setTimeout(check, 1000);
  85. })();
  86. }
  87. });
  88. };
  89. return {
  90. init : init
  91. };
  92. })();
  93. //初始化
  94. baidu.calcPageLoadTime.init();