Question

Is there a way I can get the load time of a URL or page from Jquery? For example, I make ajax request to "http://www.yahoo.com", I want to know how long it took to load the page completely. I am aware of the same domain policy. But I just want to write a simple javascript utility that can let me know page load time.

I know there are tools like YSlow etc, but I want this utility to be running continuously in browser tab and alert(javascript) alert when the page load time is beyond some threshold.

Thanks, J

Was it helpful?

Solution

Something like this should work nicely.

var startTime;
$.ajax({
    // url, type, dataType, etc
    beforeSend: function(xhr){
        startTime = +new Date();
    }
    complete: function(xhr, state){
        var latency = (+new Date()) - startTime;
        window.console.log(latency);
    }
});

OTHER TIPS

I you are using $.ajax you can set a variable with the start time in a function called by the "beforeSend" option like:

var start = (new Date()).getTime();

Then set another variable with the "complete" option like:

var finish= (new Date()).getTime();

Then compare the two to get the number of seconds like:

var secs = (finish-start)/1000;

Or once you set the start variable, use "setInterval()" to check the start variable against the current time until it exceeds a threshold.

But you know there is the "timeout" option in $.ajax too, which is covered pretty well here and may be helpful:

Determine if $.ajax error is a timeout

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top