JQuery document.ready vs Phonegap deviceready
A key point in the answer is this line from the documentation of the deviceready
event.
This event behaves differently from others in that any event handler registered after the event has been fired will have its callback function called immediately.
What this means is that you won't 'miss' the event if you add a listener after the event has been fired.
So, first move all the initialization code to the onDeviceReady function. Then first handle the document.ready. Within the document.ready if you determine that you are running in a browser, just call the onDeviceReady function, otherwise add the deviceready listener. This way when you are in the onDeviceReady function you are sure that all the needed 'ready's have happened.
$(document).ready(function() {
// are we running in native app or in a browser?
window.isphone = false;
if(document.URL.indexOf("http://") === -1
&& document.URL.indexOf("https://") === -1) {
window.isphone = true;
}
if( window.isphone ) {
document.addEventListener("deviceready", onDeviceReady, false);
} else {
onDeviceReady();
}
});
function onDeviceReady() {
// do everything here.
}
The isphone check works because in phonegap, the index.html is loaded using a file:///
url.
You should use the deviceready event to avoid funny things happening.
The docs state:
This is a very important event that every PhoneGap application should use.
PhoneGap consists of two code bases: native and JavaScript. While the native code is loading, a custom loading image is displayed. However, JavaScript is only loaded once the DOM loads. This means your web application could, potentially, call a PhoneGap JavaScript function before it is loaded.
The PhoneGap deviceready event fires once PhoneGap has fully loaded. After the device has fired, you can safely make calls to PhoneGap function.
Typically, you will want to attach an event listener with document.addEventListener
once the HTML document's DOM has loaded.
Read the documentation here:http://docs.phonegap.com/en/1.0.0/phonegap_events_events.md.html