Sunday, December 25, 2011

On the First Day of PhoneGapping: Get to deviceready faster on Android

This tip is courtesy of a question that Pamela Fox posted up over on the PhoneGap Google Group as she was wondering why it sometimes takes longer for the PhoneGap deviceready event to fire.

As all good PhoneGappers know you need to wait until you receive the deviceready event before you can call any of the PhoneGap API's. But, what has to happen before the deviceready event fires? Well here is breakdown of events that fire before deviceready:

  1. onDOMContentLoaded Internal event that is received when the web page is loaded and parsed.
  2. window.onload Body onload event.
  3. onNativeReady Internal event that indicates the PhoneGap native side is ready.
  4. onPhoneGapInit Internal event that kicks off creation of all PhoneGap JavaScript objects (runs constructors).
  5. onPhoneGapReady Internal event fired when all PhoneGap JavaScript objects have been created
  6. onPhoneGapInfoReady Internal event fired when device properties are available
  7. onPhoneGapConnectionReady Internal event fired when the connection property has been set.
  8. onDeviceReady User event fired to indicate that PhoneGap is ready
That may seem like a lot but you don't have to worry about it as you can't speed up the process any. That is, except in one area. The onNativeReady event does not fire until the the onPageFinished method gets called on the Android WebViewClient.

So anything you do that increases the amount of time before the web view understands the page is completely loaded will keep you from getting to deviceready. For instance if you are doing a lot of things  in the window.onload method it will delay deviceready. In Pamela's particular instance she was doing an XmlHttpRequest in the onload method which delayed things.

The fix and the tip in this case is to move as many things from your onload event handler to your deviceready event handler.


2 comments:

Unknown said...

Short, succinct and to the point. Thanks a lot Simon! Great article.

RR said...

Excelente Simon :)