Note: The following is good for avoiding a time delay - it's just in time. The example can be used generally by all scripts (needing it), but was particularly used with Greasemonkey. It also uses the Google chart API as an example, but this solution goes beyond to other Google APIs and can be used anywhere you need to wait for a script to load.
Using google.load with a callback did not solve the issue when using Greasemonkey to add a Google chart. In the process (Greasemonkey injected into page), the www.google.com/jsapi script node is added. After adding this element for Google's jsapi javascript, the injected (or page) script is ready to use the the google.load command (which needs to be loaded in the added node), but this jsapi script did not load yet. Setting the a timeout worked, but the timeout was merely a workaround for the Google jsapi script load's timing race with the injected/page script. Moving around where a script executes the google.load (and possibly google.setOnLoadCallback) can affect the timing race situation. The following proffers a solution that waits for the google script element to load before calling google.load. Here is an example:
// ********* INJECTED SCRIPT *********//
// add element
var gscript = document.createElement('script');
gscript.setAttribute("type", "application/javascript");
gscript.setAttribute("id", "XX-GMPlusGoogle-XX");
document.body.appendChild(gscript);
// event listener setup
gscript.addEventListener("load",
function changeCB(params) {
gscript.removeEventListener("load", changeCB);
google.load("visualization", "1", {packages:["corechart"], "callback":
function drawChart() {
var data;
// set the durationChart data (not in example)
data = new google.visualization.arrayToDataTable(durationChart);
var options = {
title:"Chart Title",
legend: {position:"none"},
backgroundColor:"white",
colors:["white","Blue"],
width: window.innerWidth || document.body.clientWidth,
height: window.innerHeight || document.body.clientHeight,
vAxis: {title: "Durations", baselineColor: "black", textStyle:{fontSize:12}},
hAxis: {title: "Days Since First Instance"},
height: ((cnt > 5)? cnt * 50 : 300),
isStacked: true
}; // options
// put chart into your div element
var chart = new google.visualization.BarChart(document.getElementById('XX-ChartDiv-XX'));
chart.draw(data, options);
} // drawChart function
}); //packages within google.load & google load
} // callback changeCB
);
// can use SSL as "https://www.google.com/jsapi";
gscript.src = "http://www.google.com/jsapi";