JQuery document.ready vs Phonegap deviceready

JavascriptJqueryCordova

Javascript Problem Overview


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?

Javascript Solutions


Solution 1 - Javascript

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.

Solution 2 - Javascript

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>

Solution 3 - Javascript

They are not the same.

jQuery.ready() is using:

document.addEventListener("DOMContentLoaded", yourCallbackFunction, false);

Source: https://code.jquery.com/jquery-3.1.1.js

Cordova/PhoneGap instructs you to use:

document.addEventListener("deviceready", yourCallbackFunction, false);

Source: https://cordova.apache.org/docs/en/latest/cordova/events/events.html

My suggestion is, that you put all the initialization code for your Cordova/PhoneGap plugins inside the callback function which is fired when the deviceready event occurs. Example:

document.addEventListener("deviceready", onDeviceReady, false);

function onDeviceReady() {
    // Now safe to use device APIs
}

Solution 4 - Javascript

@Kinjal's answer really helped me get on track, but I had to fight a lot of issues with timing.

I use Cordova device ready event to read data files for my app, a few JSON packets which drive interface building and are loaded by default inside the www folder, but might eventually be downloaded from a server, to upgrade the application database.

I have found a lot of issues because the application data structures had not enough time to initialize before routing was started.

I wound up with this solution: initialize jQuery first, call the event handler of Cordova at the end of jQuery initialization, call the application startup routine at the end of the last processing in Cordova initialization.

All this nightmare started because I needed a way to read template files for Hogan.js and could not read them with the file protocol and a simple XHR.

Like this:

$(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() {
    function readFromFile(fileName, cb) {
    	// see (https://www.neontribe.co.uk/cordova-file-plugin-examples/)
	}

	...

    readFromFile(cordova.file.applicationDirectory + 'www/views/tappa.html', function (data) {
        app.views.lastview = data;
	    app.start();
    });
}

Solution 5 - Javascript

I am using PhoneGap Build cli-6.2.0 and when I test the procedure you suggested is doesn't do anything inside function onDeviceReady().

With older versions of PGB it works!

	$(document).ready(function() { 
		window.isphone = false;
		if (document.URL.indexOf("http://") === -1 && document.URL.indexOf("https://") === -1) { window.isphone = true }
		if (window.isphone) { document.addEventListener("deviceready", this.onDeviceReady, false); } else { onDeviceReady(); }
	});
	function onDeviceReady() {
		alert( window.isphone ); 		
	}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Solution 6 - Javascript

The one does not have to exclude the other. One simple example:

$(document).on('deviceready', function() {
    console.log('event: device ready');
    $(document).on('pause', function() {
        console.log('event: pause');
    });
    $(document).on('resume', function() {
        console.log('event: resume');
    });
});

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionajaybcView Question on Stackoverflow
Solution 1 - JavascriptKinjal DixitView Answer on Stackoverflow
Solution 2 - JavascriptAbdulFattah PopoolaView Answer on Stackoverflow
Solution 3 - JavascriptTadejView Answer on Stackoverflow
Solution 4 - JavascriptmicoView Answer on Stackoverflow
Solution 5 - Javascriptuser6796773View Answer on Stackoverflow
Solution 6 - JavascriptMartin ZeitlerView Answer on Stackoverflow