Page load time of a target page or URL with jquery - javascript

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

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);
}
});

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

Related

Loading the same file via ajax 12 times at once

I hope this makes sense...
I have a page that loads the same external file 1-12 times depending on the usage. The larger load times takes up to a full minute to load the page so I'm trying to load each file via ajax, but using a loop to load the files completely hangs the server.
Here's the code I'm using so far:
function getSchedule(startday,scheduleID,scheduleView){
$.ajax({
type: 'POST',
url: siteURL+'/includes/schedule-'+scheduleView,
data: {startday:startday,scheduleID:scheduleID},
success: function(data){
$('.scheduleHolder'+scheduleID).html(data).removeClass('loading');
}
});
}
var loadSchedules = [];
var startday = $('#the_start_day').text();
var totalSchedules = $('.scheduleHolder').length;
var i = 0;
$('.scheduleHolder').each(function(){
var currentHolder = $(this);
var scheduleView = currentHolder.attr('rel');
var scheduleID = currentHolder.attr('id');
loadSchedules.push(getSchedule(startday,scheduleID,scheduleView));
if (totalSchedules==i) {
$.when.apply($, loadSchedules);
}
i++;
});
Each file should only take 2-5 seconds to load when it's loading individually, so I was really hoping the total load time could go from 60 seconds to 10 or so.
So, my question is how can I load the same file multiple times and at the same time without killing the server? Does that make sense?
I believe you need to use synchronous requests, this hopefully helps:
jQuery: Performing synchronous AJAX requests
(the wording is a bit misleading, read here: Asynchronous and Synchronous Terms )
but I can't vouch what will happen to your server with the 12 simultaneous requests - if the other end is written well, nothing.

How to trigger the reload button in jQGrid at set time intervals

I want my grid to periodically reload and get the data from the url that i specify. Every 5 seconds, i want the grid to get the current data from the url. I have already tried using setInterval and window.timeout but when i do, the grid reloads the data from the browser cache. It does not invoke the url to get the new data.
Is there a way to make the grid reload and get the new data from the url at specific time intervals ?
Basically, i want the reload button to fire automatically every 5 seconds. How can I do this ?
please help
thanks
What you need, is to use the same method you've been using before, but to prevent the browser's cache. One method of doing so, is on the server-side, add a no-cache header to to the HTTP response for that request.
Another way of doing so, is to change the request's URL, so the browser won't look it up its cache. One example is:
var url = "..."; // Your URL
url += "&nocache=" + (new Date()).getTime();
Thanks,
I figured out a way:
window.setTimeout( refreshGrid, 8000);
function refreshGrid()
{
jQuery("#refresh_list").click();
window.setTimeout(refreshGrid, 8000);
}

How to get actual time in javascript?

How to get the actual time in java script to make an online clock?
var dt=new Date();
hr=dt.getHours();
this will give the time. But its depend on the time in our computer.
I need the server time.
anybody can help me...
Thanks.
You should provide a time service and using an asynchronous request to get that time - see the example by James Padolsey here:
function getTime(zone, success) {
var url = 'http://json-time.appspot.com/time.json?tz=' + zone,
ud = 'json' + (+new Date());
window[ud]= function(o){
success && success(new Date(o.datetime), o);
};
document.getElementsByTagName('head')[0].appendChild((function(){
var s = document.createElement('script');
s.type = 'text/javascript';
s.src = url + '&callback=' + ud;
return s;
})());
}
This can be acheived in many ways, but basically what you need to do is provide a small dynamic page which prints your server's time (JSON would be a nicer approach) using PHP or any other dynamic approach and call it using AJAX in your web page as shown in James' example where the URL is your new dynamic time page.
You can write a server side program which prints the current time of the server (or as per your requirement) in PHP or ASP as below: (Just an example).
<?php
echo date("l M dS, Y, H:i:s");
?>
Then just request that page using AJAX and display in your page or do whatever with that response.
Look Getting time in javascript is not a big deal but it will give you time according to the local machine of client it can be different from the current running time....
The best solution for it is getting time from server side using ajax and using server side function such as date and time function.
For more info please see this link:- http://php.net/manual/en/function.time.php

How do I refresh dynamic content loaded into a web part inside my existing Javacscript / jQuery code?

I have the code that I've pasted below, helpfully supplied by another Stackoverflow member. I've added this code into a Kentico web part, and set the cache minutes=0, thinking that would solve my caching issue. It does, but not in IE. Is there any way I can tweak this code to refresh the content when the user comes to the page, or when we have to update the html file?
// article footer
Date.prototype.getWeek = function() {
var onejan = new Date(this.getFullYear(),0,1);
var today = new Date(this.getFullYear(),this.getMonth(),this.getDate());
var dayOfYear = ((today - onejan +1)/86400000);
return Math.ceil(dayOfYear/7)
};
jQuery(function(){
//Quotes/Testimonials
var today = new Date();
var weekno = today.getWeek();
jQuery('#quotes-wrapper').load('/quotesroller.html div.quote-'+weekno);
});
Add a cachebust parameter. Since it's a GET request, IE is annoying and always caches the contents.
var time = (new Date()).getTime();
jQuery('#quotes-wrapper').load('/quotesroller.html?_cb=' + time + ' div.quote-'+weekno);
It's probably better to use a more complex function like $.ajax() if you want to control caching on a per-request basis. Or, if you just want to turn it off for everything, put this at the top of your script:
$.ajaxSetup ({
// Disable caching of AJAX responses
cache: false
});
EDIT: To set up no cache just for this request, replace your load with this:
$.ajax({
url: '/quotesroller.html div.quote-'+weekno, //that's based on your URL above
cache: false,
success: function(result) {
jQuery('#quotes-wrapper').html(result);
}
});

$(window).unload wait for AJAX call to finish before leaving a webpage [duplicate]

This question already has answers here:
JavaScript, browsers, window close - send an AJAX request or run a script on window closing
(9 answers)
Closed 6 years ago.
Basically, once a user leaves a webpage in my application, I need to call a PHP script with AJAX, which will insert a time spent on the webpage to the database and then leave the page.
It is important to wait for the AJAX request to finish because webpages in my application are not accessible to users unless they have spent a certain time on a previous page (let's say two minutes).
Here is my jquery code:
$(document).ready(function() {
var teid = TEID;
var startTime = new Date().getTime();
$(window).unload(function() {
var timeSpentMilliseconds = new Date().getTime() - startTime;
var t = timeSpentMilliseconds / 1000 / 60;
$.ajax({
type: 'POST',
url: '/clientarea/utils/record-time',
data: 'teid=' + teid + '&t=' + t
});
});
});
How should I change it so it will wait for the AJAX request to end before leaving the webpage?
EDIT:
Or it might be better (easier) to just let the AJAX request be repeated every minute or so. Is that possible?
Well, you can set async: false on your AJAX call to make the browser wait for the request to finish before doing anything else, but note that this will 'hang' the browser for the duration of the request.
$.ajax({
type: 'POST',
async: false,
url: '/clientarea/utils/record-time',
data: 'teid=' + teid + '&t=' + t
});
From the manual:
By default, all requests are sent asynchronous (i.e. this is set to true by default). If you need synchronous requests, set this option to false. Cross-domain requests and dataType: "jsonp" requests do not support synchronous operation. Note that synchronous requests may temporarily lock the browser, disabling any actions while the request is active.
⚠ WARNING: This answer was posted in 2010 and is now outdated - the XHR specification highlights the following statement:
Synchronous XMLHttpRequest outside of workers is in the process of being removed from the web platform as it has detrimental effects to the end user’s experience. (This is a long process that takes many years.) Developers must not pass false for the async argument when current global object is a Window object. User agents are strongly encouraged to warn about such usage in developer tools and may experiment with throwing an "InvalidAccessError" DOMException when it occurs.
DevTools in Chrome has recently started warning about it, so this change (which has been coming for some years) could be imminent.
The best solution is to use navigator.sendBeacon. It is brand new functionality which is starting to get implemented in new releases of browsers. The function is available in browsers newer than Chrome 39 and Firefox 31. It is not supported by Internet Explorer and Safari at the time of writing. To make sure your request gets send in the browsers that don't support the new functionality yet, you can use this solution:
var navigator.sendBeacon = navigator.sendBeacon || function (url, data) {
var client = new XMLHttpRequest();
client.open("POST", url, false); // third parameter indicates sync xhr
client.setRequestHeader("Content-Type", "text/plain;charset=UTF-8");
client.send(data);
};
Hope this helps!
How about setting a cookie in the unload handler? The server should see it on the subsequent requests.
<script>
$(window).unload(function(){document.cookie='left_on='+(new Date())})
</script>
for me, yours is not a good idea for the browser to wait before closing...
simply because what if I really want to close it?...
if a page bother a user, it's not good...
my suggestion is, in the page, you wait for 2 minutes (if 2 minutes is the requirements), then send an ajax that the user has done his 2 minutes...
you can then check it on the server side if one has his 2 minutes or not...
It is a bad idea to try and hijack your users' browser, since it will give them a bad feeling and send them away.
If for some reason you want not to produce a new page until the user has spent a minimum time on the previous one, the best thing to do is to pilot server side, i.e. redirecting to the current page until the requested time has passed.
You don't even need to make ajax calls, just store in the session the timestamp of when the page was served, and don't show the following page until a certain amount of time has passed.
Be sure to tell the users they have to wait for a new page to be ready, maybe with a simple javascript countdown.
If you want the user to actually have the page active for a certain amount of time (i.e. not to switch to another tab/window waiting for the two minutes to elapse), well, I cannot propose an effective solution.
use onbeforeunload:
$(document).ready(function(){
window.onbeforeunload = function(){
// $.ajax stuff here
return false;
}
});
This will at least bring the user a messagebox which asks him if he wants to close the current window/tab.
I think it would be much better to use a polling technique as you suggest, though it will cause some load on the web server.
$(document).ready(function() {
var teid = TEID;
var startTime = new Date().getTime();
var ajaxFunc = function() {
var timeSpentMilliseconds = new Date().getTime() - startTime;
var t = timeSpentMilliseconds / 1000 / 60;
$.ajax({
type: 'POST',
url: '/clientarea/utils/record-time',
data: 'teid=' + teid + '&t=' + t
});
};
setInterval(ajaxFunc, 60000);
})
You'll be glad when you can use websockets :)
The jQuery.ajax() method has the option async. If you set it to false the call will block until the response comes back (or it timed out). I'm pretty shure, that calling this, will yause the browser to weit in the unload handler.
Side note: You can't rely on this to work. If the browser gives the user the option to cancel the unload handlers (which some browsers do after a while of waiting), the "time spend on site" will never be updated. You could add a timer to the site, which periodically calls a script on the server and which updates the time. You won't have an accurate value, but in your case, this isn't needed.
If you only need to know if the user was X seconds on the page You could simply set a timeout in the onload handler (using setTimeout(function, ms)) which makes a call if the user has spend the needed time. So there would be no need for a unload handler.

Categories