I want to use the google api for drawing charts in my website. However, I'm having problem with the google.setOnLoadCallback
function. Here is my code (simplified):
ATTEMPT 1: (Works fine)
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript" src="js/styling.js"></script>
<script type="text/javascript">
// Load the Visualization API and the piechart package.
google.load('visualization', '1.0', {'packages':['corechart']});
// Set a callback to run when the Google Visualization API is loaded.
google.setOnLoadCallback(helloWorld);
function helloWorld() {
alert("Hello World");
}
</script>
ATTEMPT 2: (Works fine)
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript" src="js/styling.js"></script>
<script type="text/javascript">
// Load the Visualization API and the piechart package.
google.load('visualization', '1.0', {'packages':['corechart']});
// Set a callback to run when the Google Visualization API is loaded.
google.setOnLoadCallback(helloWorld);
</script>
and in the styling.js I write:
function helloWorld() {
alert("Hello World");
}
In this case, everything works fine too.
However... ATTEMPT 3 (FAILS!)
<script type="text/javascript" src="js/styling.js"></script>
And in styling.js I write:
window.onload = function() {
// Load the Visualization API and the piechart package.
google.load('visualization', '1.0', {'packages':['corechart']});
// Set a callback to run when the Google Visualization API is loaded.
google.setOnLoadCallback(helloWorld);
}
function helloWorld() {
alert("Hello World");
}
This one does not work. Seems that the helloWorld()
is not called at all.
Why?
I'd say that the setOnLoadCallback
event is not triggered at all, since you're defining its callback when the page-loaded event has already been triggered.
Simply keep google.setOnLoadCallback(helloWorld);
and function helloWorld() {...}
outside the page-loaded callback context (both of them, otherwise you'd have context issues).
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