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.

Leave a Comment