Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

google.setOnLoadCallback() does not work from separate JS file

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?

like image 675
Yura Avatar asked Aug 28 '12 08:08

Yura


1 Answers

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).

like image 112
alexcasalboni Avatar answered Oct 21 '22 13:10

alexcasalboni