I'm currently working on an inherited project which uses Google's Visualization API (for both Python and Javascript). Since parsing the data for Gviz takes a while, I'm trying to let the page fetch a loading image and display it while the relevant charts are loading via AJAX calls.
While I could be wrong, I believe that I have been coding it correctly; below you can find the relevant code, which I have inserted into the <head>
portion of the page.
$(function() {
var dates = $("#from, #to").datepicker({
numberOfMonths: 1,
beforeShow: function() {
var other = this.id == "from" ? "#to" : "#from";
var option = this.id == "from" ? "maxDate" : "minDate";
var selectedDate = $(other).datepicker('getDate');
$(this).datepicker("option", option, selectedDate);
},
onSelect: function(dateText, inst) {
drawCharts();
}
}).change(function() {
var other = this.id == "from" ? "#to" : "#from";
if ($('#from').datepicker('getDate') > $('#to').datepicker('getDate'))
$(other).datepicker('setDate', $(this).datepicker('getDate'));
});
$("#from").datepicker("setDate", '-13');
$("#to").datepicker("setDate", new Date());
$("#weekly_cohorts").click(function() {
weekly = true;
drawCharts();
});
$("#monthly_cohorts").click(function() {
weekly = false;
drawCharts();
});
// ERROR OCCURS HERE
google.load('visualization', '1', {packages:['corechart', 'table']});
google.setOnLoadCallback(getData);
});
When I run this, Chrome's JavaScript Console displays an error message along the lines of EVENT FIRED TOO FAST
, which doesn't make sense to me according to the jQuery API.
If I call the two lines earlier (i.e., outside of the $( handler )
), however, I have no problems, but the preloading image isn't fetched until it's too late.
What's going wrong, and how do I fix it? While I could just move the script to the end of the body, I prefer to have all my stylesheet and script references in the head.
EDIT: Chrome's console no longer gives me that error, but since the page doesn't fully render before the script is called, it can't interact with the DOM. In addition, the image is still not fetched until after script execution.
Again, any ideas on how to delay script execution (triggered by the second line) from the DOMContent event to the Load event (i.e., until the page is fully rendered)?
EDIT 2: I briefly managed to get it to work as desired, but only after I restarted Chrome. However, I believe that was only because it was already stored in the local cache (i.e., HTTP Response code 304), since refreshing the page only brought back the "page not rendering before script is called" problem.