onDeviceReady not firing in PhoneGap hello world app

后端 未结 4 1998
梦如初夏
梦如初夏 2020-11-30 16:05

I\'m trying to do a simple alert(\'test\') app, but the event isn\'t being fired, this is the code:

function onLoad() {
    document.addEventListener("de         


        
相关标签:
4条回答
  • 2020-11-30 16:12

    The correct way is to make sure that document has completely loaded before adding the event listener.

    Example:

    HTML:

    <body onload="onLoad">
    

    JS:

    function onLoad() {
        document.addEventListener("deviceready", onDeviceReady, false);
    }
    
    function onDeviceReady() {
       //anything you want done after deviceready has fired
    }
    

    With jQuery you can use $(document).ready() instead of <body onload="onLoad()">

    Example:

    $(document).ready() {
        document.addEventListener("deviceready", onDeviceReady, false);
    }
    
    function onDeviceReady() {
       //anything you want done after deviceready has fired
    }
    
    0 讨论(0)
  • 2020-11-30 16:20

    I would rather take an asynchronous approach, like so:

    bindEvents: function () {
        var me = this;
    
        document.addEventListener('deviceready', function () {
            me.onDeviceReady();
        }, false);
    
        $(document).ready(function () {
            me.onDocumentReady();
        });
    },
    
    documentReady: false,
    onDocumentReady: function () {
        this.documentReady = true;
        this.checkReady();
    },
    
    deviceReady: false,
    onDeviceReady: function () {
        this.deviceReady = true;
        this.checkReady();
    },
    
    checkReady: function (id) {
        if (this.documentReady && this.deviceReady) this.load();
    },
    
    load: function () {
        // do stuff
    }
    

    This way you don't risk attaching handlers after the event has occurred.

    0 讨论(0)
  • 2020-11-30 16:28

    Put () at the end of onDeviceReady?

    onDeviceReady()
    

    Let me know if this is right guys, it worked for me when testing on the browser

    0 讨论(0)
  • 2020-11-30 16:31

    This works in Cordova apps (tested on iOS and Android) and ordinary web pages. No library (jQuery) needed.

    // Use onDeviceReady if we run in Cordova
    window.addEventListener('load', function(){
        if (window.Cordova) {
            document.addEventListener('DeviceReady', bootstrap, false);
        } else {
            bootstrap();
        }
    }, false);
    

    The Cordova documentation says that the DeviceReady event is made so, that it can't be missed. The handler will be called even if the device was ready before.

    0 讨论(0)
提交回复
热议问题