Is it possible to gracefully handle a Google Maps AJAX request timeout? - javascript

My site uses the Google Maps API. In situations where the connection to Google is slow and the map can't be rendered in a reasonable time, I'd like a Javascript callback method to be called such that I can display a useful message to the user rather than have a 'loading...' message constantly displayed.
Is this achievable?

Maybe you could have a sleep function that would check if the page has loaded yet, and after a certain time you take some sort of action.
See this posting for a situation similar to yours
setTimeout might be useful too.
so, you would have:
setTimeout((function()
{ /* test if the page is loaded,
if so, call another function
or set a flag to get out*/
}),2000); //set for 2 seconds

Related

Get dynamically changed data from web page using javascript / jquery

I'll be as direct and as specific as possible.
I'm trying to create Greasemonkey addon that would create graph of winnings/loses on: dead link
As you can see, site has front page which dinamicly shows results of wins / loses and how much did which user win/loose. What I'm trying to do is catch every new entry so I can draw some grapsh and or statistics for user / users.
When I access div/span that should have data, it turns out to be empty. I know that reason behind this is that all divs with data relevant to me are empty on load and that they get populated later on.
What I don't know is how to access that data. I can see (using firebug console) that there are GET requests executed all the time and that in those get requests is data that I need.
Can someone tell me or at least point me into right direction, how to access that data every time it gets refreshed / inserted?
You can try using the $.ajaxSuccess function to specify a function in your script to be called everytime an ajax request completes in the main page. This'll be fired for every successful ajax request, whether it pertains to the data you're talking about or not, but should allow you to re-scrape that section of the document to grab any and all data in it after every successful request. You may want to wrap your callback function in a setTimeout of some kind to make sure their own callbacks have a chance to fire and inject/modify the content before you scrape it. It should still seem instantaneous to the user if you set a timeout of, say, 1-10ms.
http://api.jquery.com/ajaxSuccess/

Sending Google Analytics event then immediately navigating away

Can I send a Google Analytics event and immediately navigate away, like so?
_gaq.push(['_trackEvent', 'foobar']);
window.location = "/";
If Google Analytics does some kind of AJAX request when this is called then it should work whether we stay on the page or not. My concern is that it seems it may sometimes just be putting stuff in an array for later processing. I'm thinking this only happens initially, when Google Analytics hasn't had time to be initialized yet, but I'd like to be certain of this.
I did a test with GA debug, and it seemed to have worked, but I'm not sure if that means it always will depending on loading speed and what not.
Can I do this and never lose any events?
The way I've done it is like so:
_gaq.push(['_trackEvent', '...', '...', '...']);
_gaq.push(function(){
// do stuff here
});
$('#logo').on('click', function(){
var curPage = window.location.href;
_gaq.push(['_trackEvent', curPage, '#logo']);
_gaq.push(function(){
window.location.href = '/';
});
});
The second push call will always run after the first one, because Google queues all push calls, so that the first one will run and complete, then the second one will run and complete. Google lets you put functions in the push method so you can queue them.
Source: https://developers.google.com/analytics/devguides/collection/gajs/#PushingFunctions
I add a slight delay (via setTimeout) if the new page isn't being opened in a new window.
I haven't had a chance to try this yet, but Google's new Universal Analytics has a hitCallback function that is executed after the data has been sent.
#mike mentions hitCallback method which is described in analytics.js documentation:
In some cases, like when you track outbound links, you might want to know when the tracker is done sending data. That way you can send a user to their destination only after their click has been reported to Google Analytics. To solve this, the send command allows you to specify a hitCallback function in the field name object that will execute as soon as analytics.js has completed sending data.
Which is fantastic, except the snippet is still in public beta. If for some reason (ahem technophobic policies ahem) you're limited to ga.js functionality, you can use this workaround:
_gaq.push(['_set', 'hitCallback', function(){
document.location='someOtherPage.html';
}]);
_gaq.push(['_trackEvent', 'category', 'event', 'value']);
Another sensible suggestion is to have a fallback to have the callback executed immediately if _gaq is not defined.
It looks like your concern about losing the event is legitimate, see this question. One answer there seems a little fragile with regards to Google changing their code, but would let you confirm the event tracking before navigating to the link. That would probably be "near-immediate".

Google Analytics: Is _gaq.push() a blocking function?

What I am trying to do is to redirect the user to the next page right after sending an event to Google Analytics:
_gaq.push(['_trackEvent', 'xxx' ...]);
window.location = 'some url ...';
The above code manages to register events because I can see them in the GA report. However I suspect that some events were lost because the browser redirects the user to the new page before the track pixel loads.
My questions are:
Does _gaq.push() block until the event has successfully reached Google's server?
If not, what is the best way to make achieve what I need?
Thanks!
Google has a support page that says you might want to add a delay after calling _gac.push, however they claim that this is to give the Google Analytics JavaScript a chance to load. They don't say that it's to ensure the request is sent.
First, delay the outbound click by a fraction of a second.
This delay will hardly be noticeable by the user, but it will provide the browser more time load the tracking code. Without this method, it's possible that a user can click on the outbound link before the tracking code loads, in which case the event will not be recorded.
I haven't checked #pixelfreak's claim of handling onbeforeunload, but it seems that's what they do.
This is my observation based on some quick research. That function is part of Google Analytic's asynchronous API, so it should not block anything, otherwise, it's not async. :)
Digging through the obfuscated ga.js, you can kinda see that the tracking is probably called onbeforeunload, which fires when you leave a page.
It really doesn't matter if the tracking pixel loads completely, it's a fire & forget. As long as the request is initiated and reaches Google's server, it'll get tracked. The response (in this case, the pixel image) is a by-product.
Maybe you can try this method, but I have not tried
_gaq.push(['_trackEvent', 'xxx' ...]);
_gaq.push(function(){location.reload()});
Just use 1 sec delay. Like this:
_gaq.push(['_trackEvent', 'xxx' ...]);
setTimeout(function(){window.location = 'some_url'}, 1000);

Alternatives to using meta-refesh for updating a page

In the past, when I've covered events, I've used a meta-refresh with a 5 minute timer to refresh the page so people have the latest updates.
Realizing that this may not be the perfect way to do it (doesn't always work in IE, interrupts a person's flow, restarts things for people with screen readers, etc.) I'm wondering if there's any other way to do handle this situation.
Is it possible to have something like ajax check every few minutes if the html file on the server is newer and have it print a message saying "Update info available, click here to refresh"?
If that's crazy, how about a javascript that just counts down from 5 minutes and just suggests a refresh.
If anyone could point me to tutorials or code snippets I'd appreciate. I just play a programmer on TV. :-)
Actually, your thought on a timed Ajax test is an excellent idea. I'm not sure that is exactly what StackOverflow uses, but it checks periodically to see if other answers have been posted and shows the user, on an interval, if there are updates.
I think this is ideal for these reasons:
It's unobtrusive - the reader can easily ignore the update if they don't care
It won't waste bandwith - no reloading unless the user chooses to
It's informative - the user knows there's an update and can choose to act on it.
My take on how - have the ajax script send off the latest post id to a script that checks for new scripts. This script can query your database to see if there are any new posts, and how many there are. It can return this number. If there are new posts, show some (non modal) message including the number of updates, and let the user decide what to do about it.
setInterval(function() {
if (confirm("Its Been 5 Minutes. Would you like to refresh")) {
window.location.reload(true);
//Or instead of refreshing the page you could make an ajax call and determing if a newer page exists. IF one does then reload.
}
}, 300000);
You can use the setInterval function in javascript.
here's a sample
setInterval("refresh function", milliseconds, lang);
You will use it passing a name to a function that actually refresh the page for the first param and the number of milliseconds between refresh for the second param (300000 for 5 minutes). The third parameter lang is optional
If the user would be interacting with the scores and clicking on things it would be a little rude to just refresh the page on them. I think doing something like a notification that the page has been updated would be ideal.
I would use jQuery and do an ajax call to the file on the server or something that will return the updated data. If it's newer than throw up a Growl message
Gritter - jQuery Growl System
Demo of what a Growl is using Gritter
A Growl message would come up possibly with whatever was changed, new scores and then an option within that message to refresh and view the new results.
jQuery Ajax information

Using a progress bar to load a time-consuming script asynchronously

I'm loading a dynamic application (which takes 20-30 seconds), and I'm trying to create a dynamic progress bar that shows the user how much of the task has been completed dynamically as the page loads.
I'm accomplishing this by setting buffer to false and having my script output a line of JavaScript as it progresses that calls a function to increment the scrollbar:
function progress(percent)
{
$("#progressbar").progressbar({value: Math.round((percent*100))});
}
This is called by a simple function call like progress(15) generated by my page and sent realtime to the browser. Someone suggested on another thread that I could optimize this by
attaching the progressbar to a .load() AJAX call, but as far as I know this ONLY returns once the whole page is loaded. Is there any way for me to use some type of asynchronous call to execute the time-consuming code and still be able to display realtime progress as it executes?
You'll need something like a ticketing system. When the client requests this time consuming operation, they are given a ticket-id.
Now they can poll the server for updates; and this can be served by a process/script different from the one actually handling the request. I'll update this answer if you add more details to the question.

Categories