2012-02-27 11 views
20

Estoy desarrollando una aplicación que usa PhoneGap y jQuery Mobile.

Ahora cuando la página se carga, entonces quiero cargar un script(.js file). Básicamente onDeviceReady o $(document).ready(). ¿Como hacer eso?

Respuesta

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

Este segundo fragmento de código es una versión ligeramente modificada del código de Google Analytics, que se utiliza para agregar una secuencia de comandos para el DOM de forma asíncrona.

ACTUALIZACIÓN

También puede establecer el atributo de una etiqueta defer<script> a true y no se ejecutará hasta que después de que el DOM se ha preparado. Vea alguna documentación aquí: https://developer.mozilla.org/en-US/docs/HTML/Element/Script

+2

Gracias Jasper.Responder es preciso ...: D –

+0

Yo, también, estaba experimentando el problema donde IE8 se estaba rompiendo en la actualización. Usar la llamada $ (document) .ready() es lo que me solucionó. Thx por la respuesta! – PhilNicholas

+1

NB: getScript es asíncrono, por lo que llamar a una función declarada dentro del script llamado puede provocar errores "indefinidos". Ver: http://stackoverflow.com/questions/1130921/is-the-callback-on-jquerys-getscript-unreliable-or-am-i-doing-something-wrong – Costa

Cuestiones relacionadas