Chapter 1. The Recipes

1.1. Determining Whether the Device Is Ready

Problem

You want to execute a PhoneGap API call, but you are unsure whether the device is ready and the application will not function if the API attempts to access the device prematurely.

Solution

The core functionalities that PhoneGap makes accessible through the JavaScript API depend on the device being ready; however, JavaScript can begin working as soon as the Document Object Model (DOM) is available. Therefore, before you perform any API call, you must ensure that PhoneGap has determined that the device is ready for use.

There are two solutions for checking whether the device is ready. For iOS, Android, and BlackBerry (version 5.0 and higher), a custom event type that you can attach to the DOM is available, and PhoneGap will trigger this event when the device is ready.

Warning

For older versions of BlackBerry, PhoneGap is unable to fire the custom event, so you must perform a basic JavaScript interval check for a Boolean variable to indicate whether PhoneGap is ready or not.

Discussion

Throughout the recipes in this book, I will always attempt to separate the code as much as possible, meaning that JavaScript will be placed in .js files, CSS in .css files, and HTML in .html files. During the prerequisites mentioned in the Preface, you should have created two folders inside of your www directory: scripts and css.

The core of the JavaScript code will be placed inside of a file called common.js. Create this file now inside ...

Get 20 Recipes for Programming PhoneGap now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.