10

I am experiencing issues with the phonegap device ready event. I am testing under iOS 6.0.

When device ready is fired, the DOM isn't ready. If I bind events to some DOM Elements in a devicereadyevent listener, I will receive no notifications because these elements do not exist at this early time.

So what are the best practices for waiting until BOTH have finished loading - DOM and phonegap?

gorootde
  • 4,003
  • 4
  • 41
  • 83
  • Are you doing it like this: `document.addEventListener("deviceready", onDeviceReady, false); function onDeviceReady() { // Now safe to use the PhoneGap API }` With your reference to 'phonegap....js' before this script. – davehale23 Oct 12 '12 at 20:24
  • 1
    deviceready event is meant to fire only after DOMContentLoaded has fired and a message from native code has also been passed to the javascript. – davejohnson Oct 15 '12 at 20:27
  • I found the perfect answer here: http://stackoverflow.com/a/14109006/1367154 – Nishanth Jul 24 '14 at 08:46

3 Answers3

3

if your are using jquery try this

$(document).ready(function(){

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

function onDeviceReady(){
    //write your function body here

}

if your are using javascript only try this

if(document.readyState === "complete") {
  document.addEventListener("deviceready",onDeviceReady,false); 
}

function onDeviceReady(){
        //write your function body here

    }
chandu
  • 2,276
  • 3
  • 20
  • 35
1

try something like this:

function onLoad(){
  document.addEventListener("deviceready", onDeviceReady, false);
}

function onDeviceReady(){
  // Now safe to use the PhoneGap API
}

Then:

<body onload="onLoad()">

This will ensure the DOM is ready before the deviceready is called

Dawson Loudon
  • 6,029
  • 2
  • 27
  • 31
0

Best experience that I've had with PhoneGap based apps is using FastClick library and initializing your app like this:

<script type="text/javascript" src="vendor/fastclick/lib/fastclick.js"></script>

<script type="text/javascript">
    window.addEventListener('load', function() {
        FastClick.attach(document.getElementById('container'));

        document.addEventListener('deviceready', function () {
            // Initialize your app here
        });
    });
</script>

You could also take a look at this answer for more details on document load event.

FastClick must be used for eliminating the 300ms delay between a physical tap and the firing of a click event on mobile browsers.

Community
  • 1
  • 1
Catalin MUNTEANU
  • 5,618
  • 2
  • 35
  • 43