2012-08-28 7 views
7

Ich möchte die Google API für das Zeichnen von Diagrammen in meiner Website verwenden. Ich habe jedoch ein Problem mit der google.setOnLoadCallback Funktion. Hier ist mein Code (vereinfacht):google.setOnLoadCallback() funktioniert nicht von separaten JS-Datei

VERSUCH 1: (Adaequat)

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

VERSUCH 2: (Adaequat)

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

und in den styling.js ich schreibe:

function helloWorld() { 
    alert("Hello World"); 
} 

In diesem Fall funktioniert auch alles gut.

jedoch ... VERSUCH 3 (VERFEHLT!)

<script type="text/javascript" src="js/styling.js"></script> 

Und in styling.js ich schreibe:

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"); 
} 

Dies funktioniert nicht. Scheint, dass die überhaupt nicht aufgerufen wird.

Warum?

Antwort

1

Ich würde sagen, dass das Ereignis setOnLoadCallback überhaupt nicht ausgelöst wird, da Sie seinen Rückruf definieren, wenn das seitengeladene Ereignis bereits ausgelöst wurde.

Halten Sie einfach google.setOnLoadCallback(helloWorld); und function helloWorld() {...} außerhalb des seitengeladenen Callback-Kontextes (beide, sonst hätten Sie Kontextprobleme).

Verwandte Themen