2012-08-28 17 views
7

Quiero utilizar la API de Google para dibujar gráficos en mi sitio web. Sin embargo, tengo problemas con la función google.setOnLoadCallback. Aquí está mi código (simplificado):google.setOnLoadCallback() no funciona desde el archivo JS separado

INTENTO 1: (funciona bien)

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

INTENTO 2: (funciona bien)

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

y en las styling.js escribo:

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

En este caso, todo funciona bien también.

Sin embargo ... INTENTO 3 (falla!)

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

Y en styling.js escribo:

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

Ésta no funciona. Parece que el helloWorld() no se llama en absoluto.

¿Por qué?

Respuesta

1

Diría que el evento setOnLoadCallback no se activa en absoluto, ya que está definiendo su devolución de llamada cuando el evento cargado de página ya se ha activado.

Simplemente mantenga google.setOnLoadCallback(helloWorld); y function helloWorld() {...} fuera del contexto de devolución de llamada cargada en la página (en ambos casos, de lo contrario, podría tener problemas de contexto).

Cuestiones relacionadas