Search code examples
javascripthtmlcordovaphonegap-plugins

Need explanation about how Cordova 'deviceready' event works


I am learning to create apps in Cordova PhoneGap and I am confused by the use of this 'deviceready' event. It is supposed to be an event specific to the Cordova API, but in the Hello World example, everything regarding it is defined in the index.js file.

var app = {
    // Application Constructor
    initialize: function () {
        this.bindEvents();
    }, // Bind Event Listeners
    //
    // Bind any events that are required on startup. Common events are:
    // 'load', 'deviceready', 'offline', and 'online'.
    bindEvents: function () {
        document.addEventListener('deviceready', this.onDeviceReady, false);
    }, // deviceready Event Handler
    //
    // The scope of 'this' is the event. In order to call the 'receivedEvent'
    // function, we must explicitly call 'app.receivedEvent(...);'
    onDeviceReady: function () {
        app.receivedEvent('deviceready');
    }, // Update DOM on a Received Event
    receivedEvent: function (id) {
        var parentElement = document.getElementById(id);
        var listeningElement = parentElement.querySelector('.listening');
        var receivedElement = parentElement.querySelector('.received');
        listeningElement.setAttribute('style', 'display:none;');
        receivedElement.setAttribute('style', 'display:block;');
    }
};

There is this script tag in the .html file though

<script src="cordova.js"></script>

All of this deviceready code just looks like an unneccessary code to me. Please someone explain to me why this 'deviceready' event is needed, and how exactly it is connected with the Cordova API


Solution

  • deviceready event is important.When you run the application the application first loading the Cordova API's,cordova plugin etc.When this loading is complete it will fire deviceready event.It is like onload event of HTML file. So,you should do your works after or on deviceready event.And cordova.js initialize the cordova API's with native platform.cordova.js will automatically generated when you build your application.<script src="cordova.js"></script> is the reference to that cordova.js file.You can get details of deviceready event here link.