JQuery document.ready vs Phonegap deviceready

ajaybc picture ajaybc · Sep 25, 2012 · Viewed 60.7k times · Source

I am making a phonegap application with jquery. I am confused whether I should wrap my entire code inside JQuery's $(document).ready() like

$(document).ready(function(){
    //mycode
});

or inside the deviceready event of phonegap like

document.addEventListener("deviceready", function(){
    //mycode
});

I am currently using document.ready but I think I may encounter problems if I try to access some Phonegap API methods inside document.ready.

Which is the best event to wrap my code in, document.ready or deviceready?

Answer

Kinjal Dixit picture Kinjal Dixit · Jan 1, 2013

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.