How can I check if cordova is ready if the deviceready event has already fired?
Asked Answered
U

2

12

In the example app cordova provides through cordova create ..., the following code listens to the deviceready event:

bindEvents: function() {
    document.addEventListener('deviceready', this.onDeviceReady, false);
},

This is nice, but what happens when the event is fired before I've had time to listen for it? As an example, replace the code from the example app (above) with the following:

bindEvents: function() {
    setTimeout(function () {
        document.addEventListener('deviceready', this.onDeviceReady, false);
    }, 2000)
},

In this example, this.onDeviceReady is never called. Would there not be a better, more reliable way to check if cordova is ready? Something like this:

bindEvents: function() {
    setTimeout(function () {
        if (window.cordovaIsReady) {
            this.onDeviceReady()
        } else {
            document.addEventListener('deviceready', this.onDeviceReady, false);
        }
    }, 2000)
},
Ugly answered 16/8, 2014 at 16:49 Comment(0)
H
27

As per the cordova documentation

The deviceready event behaves somewhat differently from others. Any event handler registered after the deviceready event fires has its callback function called immediately.

As you can see if any event Handler is attached AFTER the deviceready has fired it will be called immediately.
In a setTimeout function this is a no longer pointing to the intended object, the context is different. Therefore your handler will never be called.
You can try the below code by placing it in your <head> tag, where I am using global functions/variables (avoiding the this context issues for sake of simplicity). This should show you an alert.

<script>
    function onDeviceReady () {
     alert("Calling onDeviceReady()");
    }

    setTimeout(function () {
            document.addEventListener('deviceready', onDeviceReady, false);
    }, 9000);
</script>
Hughmanick answered 16/8, 2014 at 18:42 Comment(1)
Right you are. I had totally misinterpreted the issue here.Ugly
E
-1

frank answer really works. But the right way to handle this is not by adding timeout.

The deviceready Event Handler will be created while DOM is loading. So to use the event we should wait untill DOMContentLoaded. after that we can add listener to the deviceready event

document.addEventListener("DOMContentLoaded", function() {
    //alert("Calling DOMContentLoaded");
    document.addEventListener('deviceready', function(){
        //alert("Calling onDeviceReady()");
        callFirebase();
    }, false);
});
Endicott answered 20/9, 2017 at 5:23 Comment(1)
I think you missed the point of the accepted answer: @Hughmanick demonstrates that an event listener can be created at any time for deviceready - even 9 seconds after the page has loaded. So, no need to wait for any event (including DOMContentLoaded.)Redwood

© 2022 - 2024 — McMap. All rights reserved.