2012-02-27 9 views
20

Sto sviluppando un'applicazione utilizzando PhoneGap e jQuery Mobile.

Ora, quando la pagina viene caricata, voglio caricare un script(.js file). Fondamentalmente onDeviceReady o $(document).ready(). Come farlo?

risposta

40
//wait for document.ready to fire 
$(function() { 

    //then load the JavaScript file 
    $.getScript('script.js'); 
}); 

http://api.jquery.com/jquery.getscript

//create a callback function 
function myCallback() { 


    //create a script element and set it's type and async attributes 
    var script = document.createElement('script'); script.type = 'text/javascript'; script.async = true; 

    //set the source of the script element 
    script.src = 'script.js'; 


    //add the script element to the DOM 
    var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(script, s); 

} 

//add event listener for the deviceready function to run our callback function 
document.addEventListener("deviceready", myCallback, false); 

http://docs.phonegap.com/en/1.4.1/phonegap_events_events.md.html#deviceready

Questo secondo frammento di codice è una versione leggermente modificata del codice di Google Analytics, utilizzato per aggiungere uno script al DOM in modo asincrono.

UPDATE

È inoltre possibile impostare l'attributo di un defer<script> tag per true e non sarà eseguito fino a dopo il DOM è stato preparato. Vedere alcuni documenti qui: https://developer.mozilla.org/en-US/docs/HTML/Element/Script

+2

Grazie a Jasper.Rispondi accurati ...: D –

+0

Anch'io ho riscontrato il problema di interruzione di IE8 all'aggiornamento. L'utilizzo della chiamata $ (document) .ready() è ciò che ha risolto per me. Grazie per la risposta! – PhilNicholas

+1

NB: getScript è asincrono, quindi richiamare una funzione dichiarata all'interno dello script chiamato può causare errori "non definiti". Vedi: http://stackoverflow.com/questions/1130921/is-the-callback-on-jquerys-getscript-unreliable-or-am-i-doing-something-wrong – Costa

Problemi correlati