Three Quick Performance Tips for PhoneGap and jQuery Mobile

For even more mobile performance tips - this time in JavaScript - check out my upcoming So Cal Code Camp Session: 5 Quick JavaScript Performance Improvement Tips.

PhoneGap when combined with jQuery Mobile sometimes exhibits sluggish performance. Here are three tips to improve its performance. I have tested these tips under iOS and Android, and they work. I am still trying to find more, but these should help for now.

Prevent Default Event Behavior

The system can spend a lot of time bubbling through events. Once your code has handled an event use both event.preventDefault(); and return false; to stop the system code from also handling the event. This is by far the biggest performance improvement that I've found. Adding these two statements to the event handler for the <button> tap dramatically improved the performance of the JQMCalculator app from a previous tutorial.

Cache jQuery Selectors

Searching the DOM is taxing. Once you have used jQuery to find an element or elements, store it a variable. By convention we begin a variable with a dollar sign, $, when it is holding the results of a jQuery selector.

Narrow jQuery Selectors

Similar to the previous tip, searching the DOM is taxing, so make sure to search as little of it as necessary. Don't search the entire document when all you are looking for lies with a <div>. When using jQuery Mobile, you can restrict the search to the active page by using $.mobile.activePage.

With the variable $entryLine, we narrow the selector by restricting it to the active page. Remember: jQuery Mobile can have multiple pseudo-pages in memory simultaneously. Restricting the selector to the current page can eliminate a lot of unnecessary searching.

With the variable, $li, we do another form of narrowing. We search only the <li> tags which are descendants of id #paperTape. Id selectors are usually the fastest ones in jQuery since they translate directly into a JavaScript method, document.getElementById().

Summary

Let me know if these tips help your app, and if you have some tips please share them. BTW: These tips will help even if you are simply using jQuery Mobile without PhoneGap.

Popular Posts