在javascript中监控单页加载时间

时间:2013-10-28 08:53:23

标签: javascript ajax monitoring performance-testing single-page-application

我有一个现有的单页Web应用程序,我无法更改代码。有些用户抱怨申请表现不佳。

我想以这种方式监控加载时间:

  1. 在页面上记录点击的时间戳
  2. 在ajax请求和其他一些javascript魔法完成之后,记录完成页面渲染的时间戳
  3. 计算两个时间戳之间的差异并将其发回服务器。
  4. 我可以轻松地使用jQuery执行第1步和第3步,但是我不确定步骤2的最佳方法是什么?

    由于这似乎是一个非常明显的场景,是否有标准工具集来执行此类监控?

5 个答案:

答案 0 :(得分:1)

这有助于:

function onLoad() { 
  var now = new Date().getTime();
  var page_load_time = now - performance.timing.navigationStart;
  console.log("User-perceived page loading time: " + page_load_time);
}

答案 1 :(得分:1)

您可以使用jQuery提供的全局ajaxStop事件。

var start = +(new Date());
$(document).ajaxStop(function() {
    var diff = +(new Date()) - start;
    // do logging
});

这将不包括上次AJAX调用后执行的代码,但如果在最后一次调用之前发生的事情包含预期的瓶颈,那么这将非常有用。

答案 2 :(得分:0)

这可以通过以下方式实现......

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
    <script src="jquery.min.js"></script>
    <script type="text/javascript">
        var startTime, endTime, timeDifference;
        function doIt() {
            var startTime = new Date().getTime();
            $.ajax({
                type: 'post',
                url: 'a.php',
                success: function (resp) {
                    endTime = new Date().getTime();
                    timeDifference = endTime - startTime; //Time Difference is stored in milliseconds
                }
            })
        }
    </script>
</head>
<body>
<button style="position: absolute; top:60px" onclick="doIt()">start</button>
</body>
</html>

答案 3 :(得分:0)

这不是一个完美的解决方案,但以下代码正在运行。它在用户点击时启动计时器。 checkHTML函数监视页面内容的更改。

var timeLogging = new Array();
var timeStart;

$(document).click(function() {
    initLogEvent();
});

function initLogEvent() {
    caption = $(".v-captiontext:first").text();
    timeStart = +(new Date());
    timeLogging.push(new Array(0,0));
    timeLogging[timeLogging.length - 1][0] = timeStart;
}

initLogEvent();
// Start a timer to check the changes in html
window.setInterval(checkHtml, 250);
// Start a timer to create the reports
window.setInterval(sendReport, 1000);


var html;
function checkHtml() {
    current = $("body").html();
    if (current != html) {
        html = current;
        var diff = +(new Date()) - timeStart;
        timeLogging[timeLogging.length - 1][1] = diff;
    }
}

function sendReport() {
    if (timeLogging.length > 3) {
        console.log(timeLogging);
        // Do additional stuff with the collected data
        for (i = 0; i <= timeLogging.length; i++) {
            timeLogging.shift();
        }
    }
}

答案 4 :(得分:0)

您是否将所有应用程序的标记保留在页面中,即使它被隐藏了?如果是这样,你可能会窒息浏览器的内存。我建议学习几年前在Bing和谷歌先驱这样的localStorage中卸载你的标记。我在发现这项技术的那天写了一篇关于它的博客,从那时起我就开始使用它了。

http://love2dev.com/#!article/Use-Local-Storage-to-Make-Your-Single-Page-Web-Application-Rock