Hi I want to check response times of website. Here is my code, I got some values but doesn't show reality. What is the problem with these codes. Is it sth related with cache?? Furthermore how to show if page doesn't exit or unavailable.
<script type="text/javascript" src="jquery.min.js"></script> <script type="text/javascript">
var start = new Date();
$.ajax ({
url: 'http://www.example.com',
complete : function()
{
alert(new Date() - start)
},
});
</script>
The code itself is fine assuming that the code is running on the same origin as the one it's checking; you can't use ajax cross-origin unless both ends (client and server) support and are using CORS.
It could be caching, yes, you'd have to refer to the browser tools (any decent browser has a Network tab or similar in its developer tools) to know for sure. You can also disable caching by setting cache: false in the ajax call (see the ajax documentation for details), although that's a somewhat synthetic way to do it. A better way would be to ensure that whatever URL you're using for this timing responds with cache headers telling the browser (and proxies) not to cache it.
You can tell if the page doesn't exist or is "unavailable" (whatever that means) by hooking the error function and looking at the information it gives you:
var start = new Date();
$.ajax ({
url: 'http://www.example.com',
error : function(jqxhr, status, ex) {
// Look at status here
},
complete : function()
{
alert(new Date() - start)
},
});
The arguments given to error are also described in the docs linked above.
You can't do this due to the same origin policy.
One trick would be to create an image and measure the time until the onerror event fires.
var start = new Date();
var img = new Image();
img.onerror = function() {
alert(new Date() - start);
};
img.src = 'http://www.example.com/';
Append a random number to the url to prevent caching.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With