Unit - 5
Advanced Tools, Techniques
A. J2ME OVERVIEW
• The Java development team increases the capabilities of Java to scale back the complexity of developing a multi-tier application.
• The team grouped features of Java into three editions, each with a software development kit (SDK).
• the first edition of Java, called the Java 2 Standard Edition (J2SE), consists of application programming interfaces (APIs) needed to make a Java application or applet.
• The Java 2 Micro Edition (J2ME) consist of the API used to create applications for small computing devices, with wireless Java applications.
• the event team at Sun worked on Java within the first 1990s to affect the programming needs of the fledgling embedded computer market, but that effort was sidetracked by more compelling opportunities presented by the online .
• As those opportunities were addressed, a brand new breed of portable communications devices opened other opportunities at the turn of the century. Cell phones expanded from voice communications devices to voice and text communications devices.
• Pocket electronic telephone directories evolved into personal digital assistants. Chipmakers were releasing new products at now that were designed to transfer computing power from a private computer into mobile small computers that controlled gas pumps, cable television boxes, and an assortment of other appliances.
• J2ME could also be a reduced version of the Java API and Java Virtual Machine that's designed to figure within the sparse resources available within the new breed of embedded computers and microcomputers.
B. Inside J2ME
• Consumers expect equivalent software and capabilities found on their desktop and laptop computers to be available on their cell phones and private digital assistants.
• Developers ready to make applications that run on cell phones, personal digital assistants, and various consumer and industrial appliances must strike a balance between a thick client and a thin client.
• A thick client is front-end software with the logic to handle an big amount of data processing for the system.
• a thin client is front-end software which depends on back-end software for much of the system processing.
• Processing on the wireless device involve two steps: First the software performs a simple validation process to assure that every one fields on the shape contain information.
• Next order is transmitted to the back-end system.
• The back-end system handles adjusting account balances and other steps present in processing the order.
• A confirmation notice is returned by the back-end system to the wireless device, to display the confirmation notice on the screen.
• A key advantage of using J2ME is that J2ME is compatible with all Java-enabled devices. A Java-enabled device is any computer that runs the Java Virtual Machine.
C. J2ME Architecture
The modular design of the J2ME architecture enables an application to be scaled supported constraints of alittle computer . J2ME architecture with layers pleaced above the native OS , collectively mentioned because the Connected Limited Device Configuration (CLDC).
The CLDC, which is installed on top of the OS , forms the run-time environment for little computing devices. The J2ME architecture comprises three software layers . The first layer is that the configuration layer that has the Java Virtual Machine (JVM), which directly interacts with the native OS . The configuration layer also handles interactions between the profile and thus the JVM.
The second is profile layer, contains the minimum set of application programming interfaces (APIs) for the tiny computer. The third layer is that the Mobile Information Device Profile (MIDP). The MIDP layer consist of Java APIs for user network connections, persistence storage, and user interface . It has access to CLDC libraries and MIDP libraries.
A small computer has two components supplied by the primary equipment manufacturer (OEM). These are classes and applications. OEM classes are employed by the MIDP to access device related features like sending and receiving messages and accessing device-specific persistent data. OEM applications are programs which are provided by the OEM as address book.
D. Run-Time Environment
A MIDlet is defined with a minimum of a single class that's derived from the javax .microedition.midlet.MIDlet abstract class. Developers bundle related MIDlets into a MIDlet suite, which is present within an equivalent package and implemented at same time on a small computer. All MIDlets within a MIDlet suite are consider a group and which is installed and uninstalled as a group.
Members of a MIDlet suite share resources of the host environment and share similar instances of Java classes and run within a same JVM. This suggests if three MIDlets from a same MIDlet suite run a similar class, just one instance of the category is made at a time within the Java Virtual Machine. A benefit of the connection within MIDlet suite members is they share an equivalent data, containing data in persistent storage like user preferences.
Sharing data within MIDlets exposes each MIDlet to data errors caused by concurrent read/write access to data. This risk is overcome by synchronization primitives on the MIDlet suite level that restrict access to volatile data and persistent data. A MIDlet suite is installed, executed, and removed by the application manager running on the device. The application manager makes the Java archive (JAR) file and therefore the Java application descriptor (JAD) file available to members of the MIDlet suite.
Inside the Java Archive File:
All the files need to implement a MIDlet suite present within a production package called a Java archive (JAR) file. These files contain MIDlet classes, graphic images, and the manifest file. The manifest file contains a listing of attributes and related definitions which are employed by the application manager to put in the files contained within the JAR file on small computer. Nine attributes are defined within the manifest file.
The manifest file’s extension is change to .mf when the MIDlet is ready for deployment.
MIDlet-Name: Best MIDlet
MIDlet-Version: 2.0
MIDlet-Vendor: MyCompany
MIDlet-1: BestMIDlet, /images/BestMIDlet.png, Best.BestMIDlet
MicroEdition-Profile: MIDP-1.0
MicroEdition-Configuration: CLDC-1.0
The MIDlet-n attribute with three values which describe the MIDlet. A comma separates each value. The primary value is that the name of the MIDlet, which is BestMIDlet. Next is an optional value which specifies the icon that was used with the MIDlet. During this example, BestMIDlet.png is that the icon. The icon must be within the PNG image format and therefore the last value for the MIDlet-n attribute is that the MIDlet class name, which is Best.BestMIDlet. The application manager uses the category name to load the MIDlet.
Inside the Java Application Descriptor File
A JAD file provide the application manager with extra content information related to the JAR file to work out whether the MIDlet suite is implemented on the device. A JAD file is comparable to a manifest therein both contain attributes that are name:value pairs. Name:value pairs present in any order within the JAD file. There are five system attributes for a JAD file:
MIDlet-Name
MIDlet-Version
MIDlet-Vendor
MIDlet-n
MIDlet-Jar-URL 18
A developer contains application attributes during a JAD file. An application attribute is a name:value pair that with a value unique to the application.
E. MIDlet Programming
Programming a MIDlet is same as to making a J2SE application therein you define a category and related methods. A MIDlet is a class that extends the MIDlet class and is that the interface between application statements and run-time environment, which is controlled by the application manager. A MIDlet class contains three abstract methods that are called by the application manager to manage the life cycle of the MIDlet. These abstract methods are startApp(), pauseApp(), and destroyApp().
The startApp() method is called by the application manager when the MIDlet is started and contains statements that are executed when the application begins execution. The pauseApp() method is named before the application manager temporarily stops the MIDlet. The application manager restarts the MIDlet by recalling the startApp() method. The destroyApp() method is named before the termination of the MIDlet by the application manager.
Public class BasicMIDletShell extends MIDlet { public void startApp() { } public void pauseApp() { } public void destroyApp( boolean unconditional) { } }
Both the startApp() and pauseApp() methods are public and no return value nor parameter list. The destroyApp() method is a public method with no return value. The destroyApp() method features a boolean parameter that's set to true if the termination of the MIDlet is unconditional, and false if the MIDlet can throw a MIDletStateChangeException telling the application manager that the MIDlet doesn't want to be destroyed just yet.
At the middle of each MIDlet are the MIDP API classes employed by the MIDlet to interact with the user and handle data. The data-handling MIDP API classes helps the developer to perform four sorts of data routines: write and read persistent data, store data in data types, receive data from and send data to a network, and interact with the tiny computing device’s input/output features.
Event Handling
A MIDlet is an event-based application. All routines executed within the MIDlet are worked in response to an event reported to the MIDlet by the application manager. The startApp() method during a MIDlet contains a statement that displays a screen of knowledge and prompts the user to enter a multiple from among one or more options.
A Command object is employed to present a user with a many options to decide on from when a screen is displayed. Each screen contains CommandListener. A CommandListener monitors user events with a screen and causes the acceptable code to execute supported the present event.
User Interfaces
The design of a user interface for a MIDlet based on the restrictions of a small computer. An upscale user interface contains the subsequent elements, and a tool with a minimal user interface having subset of those elements as determined by the profile used for the device. A Form is that the most ordinarily performed user interface element found during a MIDlet and is employed to contain other user interface elements. Text is placed on a form as a StringItem, a List, a ChoiceGroup, and a Ticker.
A StringItem contains text that present on a form that can't be changed by the user. a list is an itemized options list from which the user can choose an option. A ChoiceGroup was a related itemized options list. And a Ticker is text that's scrollable. A user enters information into a form by using the choice element, TextBox, TextField, or DateField elements. The choice element returns an option that the user selected.
TextBox and TextField elements collect textual information from a user and enable the user to edit information that present in these user interface elements. The DateField is analogous to a TextBox and TextField except its contents are a date and time. An Alert is a special Form that's wont to alert the user that an error has occurred. An Alert is limited to a StringItem user interface element defines the character of the error to the user.
Device Data
Small computing devices don’t have the resources necessary to run an onboard database management system (DBMS). A MIDlet use MIDP class RecordStore and two MIDP interfaces RecordComparator and RecordFilter to write down and read persistent data. A RecordStore class contains methods wont to write and read persistent data within the sort of a record. Persistent data is read from a RecordStore by using either the RecordComparator interface or the RecordFilter interface.
F. J2ME Wireless Toolkit
The J2ME Wireless Toolkit is employed to develop and test J2ME applications by selecting buttons from a toolbar.
Building and Running a Project
After downloading the J2ME Wireless Toolkit from the site ,create a new project by selecting the New Project button from the toolbar. You’ll be prompted to enter a project name and class name. Enter Hello World because the project name and greeting. HelloWorld because the class name, which is the name of the primary MIDlet that's related to the project. After selecting the Create Project button, the J2ME Wireless Toolkit automatically creates a directory structure for the project and also creates the manifest file and JAD file.
The User Defined tab contains optional attributes specific to your application. This tab is going to be empty until you decide on the Add button and insert your own attributes. The MIDlets tab lists MIDlets of your project. Notice that the HelloWorld MIDlet is listed within the tab, which is that the MIDlet you entered because the class name when beginning the project.
A well organized file structure is created for your project as results of starting a new project. Within the WTK104 directory, you’ll see apps subdirectory during which the projects you create are stored. Browse the apps subdirectory to ascertain a subdirectory called Hello World, the name that you simply gave to your project. A subdirectory of the apps directory is made for each project. And within the project’s subdirectory is another set of subdirectories. These are
■src, containing source code
■bin, containing the manifest.mf file, JAD file, and JAR file.
■classes, containing the compiled classes
■tmpclasses, containing the pre-verify classes
■res, containing image, data, and other files required by the application.
Hello World J2ME Style
Create the primary MIDlet once the Java development kit, Connected Limited Device Configuration (CLDC), and Mobile Information Device Profile (MIDP) are installed.
Lets begin by creating a directory structure within which you'll create and run MIDlets. Create the HelloWorld MIDlet now. Enter the code into a text editor like Notepad, and save the enter the j2me\src\greeting directory as HelloWorld.java.
The HelloWorld MIDlet performs three functions that are found in all MIDlets. These are to display a text box and a command on the screen, then listens to events that occur while the MIDlet is running. The HelloWorld MIDlet is made by defining a class called HelloWorld which extends the MIDlet class and implements a CommandListener. The HelloWorld class contains three private data members and 4 methods.
The data members are a Display object, a text box, and a command. The methods are startApp(), pauseApp(), and destroyApp(). The fourth method is named commandAction() and is invoked by the application manager when an event occurs.
The final statement within the startApp() method associates the TextBox object with the Display object by calling the setCurrent() method of the Display object and passing the setCurrent() method the TextBox object. Before invoking the notifyDestroyed() method, a MIDlet have completed its own garbage pickup .
Compiling Hello World
The Hello World source code files must saved within the new j2me\src\greeting directory as HelloWorld.java. The primary step is to use the Java compiler to transform the source file into a class file. The second step is to preverify the class file. The preverification generates a modified class file. Make j2me\src\greeting the present directory, then enter the subsequent command at the command line. Javac -d d:\j2me\tmp_classes -target 1.1 -bootclasspath d:\j2me\midp1.0.3fcs\classes HelloWorld.java.
Running Hello World:
A MIDlet was tested in an emulator before being downloaded to a small computer . An emulator is software that simulates how a MIDlet will run during a small computing device. There are two ways to run a MIDlet. These are either by invoking the MIDlet class or by creating a JAR file, then running the MIDlet from the JAR file. Click the proper telephone handset icon to close the MIDlet. Midp -classpath d:\j2me\classes greeting.HelloWorld.
G. Multiple MIDlets during a MIDlet Suite
In the world , multiple MIDlets are distributed during a single MIDlet suite. The application manager then displays each MIDlet as a menu option, enabling the user to run one among the MIDlets.
A. Supported Technologies
We are getting to test JavaScript compatibility within the following pages, but making JavaScript work requires quite just support for the language. There are many technologies (or APIs) that are bundled with JavaScript, but they're optional and cannot work on all devices.
Document Object Model
DOM may be a set of conventions for manipulating, browsing, and editing XML and HTML documents employing a set of API conventions which will be implemented in many languages. In fact, although many developers think that DOM is a JavaScript thing, this is often wrong. There are DOM APIs for PHP, .NET, Java, and lots of other languages.
Even if you’ve never heard about DOM, odds are good that you’ve used it. If you’ve used the well-known document.getElementById function, for instance , you were using DOM.
Today, DOM may be a W3C specification. The foremost compatible versions for web use are the DOM Level 2 Core specification (DOM2CORE) and therefore the subspecification DOM Level 2 HTML (DOM2HTML) for HTML and XHTML documents.
With DOM, we will browse the XHTML document structure and make changes and additions dynamically from JavaScript without refreshing the page.
A mobile browser are often JavaScript-compatible but without DOM functionality. There also are some browsers that allow us to browse the document tree but to not modify it on the fly.
Ajax
Ajax, originally an acronym of Asynchronous JavaScript and XML, may be a technique that involves making asynchronous server requests without refreshing the page, interrupting the user’s activity, changing the browser’s history, or losing global state variables.
The magic behind Ajax is named XMLHttpRequest; it's a native JavaScript object available in compatible devices that was supported an ActiveX object created by Microsoft in Internet Explorer 5.0.
JSON
JavaScript Object Notation may be a lightweight data interchange format known to be compatible with almost every language in common use. It's sometimes used in JavaScript as a replacement for other transport formats, like XML. JSON are often utilized in Ajax requests. We'll mention differences within the mobile browsers’ implementations during a while.
B. HTML 5 APIs
With the upcoming HTML 5 standard, JavaScript will support some new APIs for client scripting and document work. Mobile browsers are already adopting a number of these new APIs, although the standard remains in discussion.
Following are the some APIs:
• Offline applications
• Client storage
• Canvas drawing
• Workers
• Geolocation (available as another W3C standard)
C. Platform Extensions
There are other extensions available for web applications on some devices, and lots of other JavaScript APIs are supported in installed applications. These JavaScript APIs can include support for:
• Messaging
• Address book management
• Geolocation
• Gallery
• Camera
• Calendar
• Device status information
• Native menus
D. Coding JavaScript for Mobile Browsers
First of all, let’s see what's happening with basic JavaScript compatibility (variables, functions and basic alert functionality) with mobile browsers.
Table. JavaScript support compatibility table
We need to pay attention to proxied browsers, like Opera Mini. Remember that these browsers render our websites on their servers and send compressed and compiled content to the clients. The clients aren’t really browsers capable of rendering an XHTML file or JavaScript code.
When we mention mobile JavaScript, we are talking about an equivalent code you already know: a script tag including some code or a script tag with an external source. Many browsers accept the old way of defining the script language (language="javascript"), and lots of of them also accept not defining the language in the least (using script alone):
<script type="text/javascript">
// Code goes here
</script>
<script src="mysource.js" type="text/javascript">
You can execute JavaScript code in four different ways:
• From a script tag
• From an event handler
• From a link using the javascript: URL protocol
• From a bookmarklet using the javascript: URL protocol
Table. Script execution compatibility table
If a device isn't compatible with JavaScript, it'll show the JavaScript code to the user as text. We avoid this problem by inserting an HTML comment just after the script tag:
<script type="text/javascript">
<!--
// JavaScript code here
-->
</script>
A. Coding JavaScript for Mobile Browsers
First of all, let’s see what's happening with basic JavaScript compatibility with mobile browsers. Table illustrates the present levels of support on the various platforms.
We need to pay special attention to proxied browsers, like Opera Mini. Remember that these browsers render our websites on their servers and send compressed and compiled content to the clients. The clients aren’t really browsers capable of rendering an XHTML file or JavaScript code.
When we mention mobile JavaScript, we are talking about an equivalent code you already know: a script tag including some code or a script tag with an external source. Many browsers accept the old way of defining the script language (language="javascript"), and lots of them also accept not defining the language in the least:
<script type="text/javascript">
</script>
<script src="mysource.js" type="text/javascript">
B. Code Execution
You can execute JavaScript code in four different ways:
• From a script tag
• From an event handler
• From a link using the URL protocol
• From a bookmarklet using the URL protocol
C. JavaScript Mobile Compatibility
As you progress into JavaScript on the mobile web, you’ll want to check compatibility and use some old-fashioned features.
Feature detection
The simplest way to detect if a feature, API, function, or object is out there to use is to ask if it exists employing a simple if statement:
If (object) {
}
For example:
If (document.getElementById) {
}
Standard dialogs
JavaScript supports a listing of standard dialogs that are undervalued in modern desktop websites, often being replaced by Dynamic HTML or UI libraries. They create great standard dialogs to be used in mobile websites.
The list of accessible dialogs is:
• alert, for showing a message
• confirm, for receiving a Boolean response from the user
• prompt, for receiving a string from the user
• print, for sending the web page to the printer
• find, for invoking the find feature of the browser
The find dialog isn’t really a part of the standard, but it works in almost every non-IE desktop web browser on the market. This dialog receives three optional parameters: the text to search out, a case-sensitive Boolean, and a backwards Boolean. It should be avoided in mobile browsers. Most of them don’t have an enquiry feature.
The print dialog isn’t mobile compatible, for obvious reasons, but the alert, confirm, and prompt dialogs are compatible with almost every JavaScript-enabled mobile. I encourage you to use them when needed. Employing a standard dialog will always be quicker, simpler, nicer, and more compatible than using the other solution for an equivalent task.
Common problems with the alert dialog are the usage of the carriage return for multiline text, and the way to display text that’s too big to suit within the available space. For the first problem, it's common in desktop JavaScript to use the \n (newline) escape special character. Let’s see what happens with both problems in mobile browsers.
Writing to the document
The function allows us to dynamically write HTML code to a document while it's rendering. This was a really common technique within the ’90s, but there are a lot of reasons for not using it in modern websites. Today, the well-liked technique is to control the document using DOM after the onload event.
That said, within the mobile space sometimes it's better to not affect DOM, so performing operations can avoid tons of problems.
For example, you'll create a year selection list dynamically to save lots of bytes within the original document. For rendering performance purposes, it's better to use with the entire HTML at an equivalent time instead of partially writing a tag with many lines. The subsequent code demonstrates this technique:
Platform detection
JavaScript features a native navigator object representing the client browser on which the code is running.
The navigator object has many properties, but the foremost useful are appName (the browser’s name), appVersion (the browser’s version), mimeTypes (an array of supported MIME types), plugin (an array of supported plug-ins for object tag), platform (the operating system), and userLanguage.
Generally, we'll use the string’s indexOf function to verify whether a number of these attributes have the values we are trying to find . For example:
Var android = (navigator.platform.indexOf("android")>=0);
If (android) {
// Do something
}
Window size
JavaScript has two objects associated with sizes: document.documentElement and screen. The primary is said to the dimensions of the current document’s viewport, and therefore the second to the entire screen of the device. At the time of writing, there's no browser that permits windows smaller than the entire screen. We will create web widgets for the home screen on many devices, but this is often another situation.
The screen object has four properties: width, height, availWidth, and availHeight. The last two ask the dimensions available taking under consideration the space employed by the OS toolbars. Within the mobile space, they're an equivalent because the width and height values.
The most commonly used way to get the window size is via document.documentEle ment.clientWidth and document.documentElement.clientHeight.
The only way for these values to change while the page is loaded is in response to an orientation change, on compatible devices.
History and URL management
JavaScript features a few standard mechanisms for browser history management: the loca tion and history objects. The location object has several properties regarding the address, like href for the entire URL and hash for the anchor a part of the URL, if present . Changing the location.href property will redirect the browser to a different page, on compatible devices. It's two useful methods:
The history object features a few not-very-useful properties and three methods: back(), go(number), and forward(). The back method is that the most ordinarily used, for emulating a back button:
<!-- As a button -->
<input type="button" onclick="history.back()" value="Back" />
<!-- As a link -->
<a href="javascript:history.back()">Back</a>
We are designing for mobile browsers, and sometimes the users are going to be browsing in full-screen mode with none browser buttons in view . A link or button for going back are going to be more useful here than in desktop websites.
Manipulating windows
One of the foremost popular features of JavaScript is that the usage of window.open for opening the classic pop-up windows. For mobile browsers, the usage of this technique isn't ideal, for several reasons. Many browsers can’t open multiple windows, and that we cannot define any attributes for the pop-ups; they're going to just be full-sized, just like the main window.
Communication between the opener and therefore the pop-up also often doesn't work well. Closing pop-ups are often problematic on browsers that treat the new window as a normal page and not a pop-up, because window.close only works on pop-ups.
So, if you'll , avoid using pop-ups. If you actually need one for a few reason, open the window after an onclick event and remember that some mid- and low-end devices won't show your window.
JavaScript debugging is one among the foremost painful activities in mobile web development. Every browser features a different JavaScript engine, and sometimes code that works on one device doesn’t work on another. Typical desktop JavaScript techniques should be used first to debug logic problems in our code.
This includes using the developer tools from Chrome, Safari, or Internet Explorer, or the classic Firebug for Firefox. But simply because everything works during a desktop browser doesn’t mean that it'll add a mobile browser. Rich Internet Application techniques are the worst problem areas.
Browser-based solutions
Some mobile browsers offer developer tools for JavaScript debugging or console logging features.
Safari on iOS Debug Console
Safari includes a debugging console that we will activate (both in simulators and on real devices) by getting to Settings→Safari→Developer→Debug Console. With the debug console activated, you'll find a new 60-pixel-high toolbar below the highest toolbar of the browser.
Clicking this toolbar opens a full-screen Console window, as shown in Figure, where you'll see advice, warnings, errors, and console output, which you'll filter into HTML, JavaScript, and CSS categories. For better detail reading, use landscape orientation.
Figure. Once you activate the debug console you'll see the console toolbar (left), which you'll click on to access a details list (right).
From JavaScript, you'll send messages to the console using the log, warn, error, and info methods of the console global object available within the iPhone browser. All of those methods receive a string. The difference between them is that the icon won’t to show the text. For example:
Console.log("This text will appear on the Console");
Opera Dragonfly
From Opera Mobile 9.5, we will debug mobile web applications using the remote debugging tool Dragonfly. To use this tool you'll need Opera 9.5 or afterward you’re desktop. You’ll open Dragonfly by getting to Tools→Advanced→Developer Tools and checking the Remote Debug option. When you’re done, enter opera:debug in your Opera Mobile browser and specify your desktop IP address . You’ll then have access to an equivalent debugging features (DOM, CSS, and JavaScript) that you simply would if you were debugging an area desktop file.
Android Debug Bridge.
Android doesn’t have as nice a console output as Safari on iOS, but we will still read the console errors and even use an equivalent console object using the Android Debug Bridge (adb). Adb may be a command-line application available within the tools folder of your SDK.
BlackBerry web development tools
BlackBerry offers two plug-ins which will be wont to develop and also to debug, profile, and package web applications. Both provide JavaScript debugging with breakpoints, Ajax requests visibility, and time-to-load reporting for web page .
Widget debuggers.
The BONDI SDK for widgets offers a remote debugging feature which will be used from the Google Chrome Developer Tools. WRT plug-ins for Aptana Studio and Visual Studio also support debugging over the emulator (remember that it's not the important engine). The LG SDK and therefore the BlackBerry web development tools have great debugging tools for widgets, too.
JavaScript solutions
There are some scripts that job as a sort of debugger, including DOM and CSS inspectors and a few that job for JavaScript debugging, too. The mobile compatibility for these tools is complicated, though, due to the shortage of space on the screen to point out all the knowledge.
There also are some Ajax-based solutions which will work better, allowing you to look at the debug results and panes from a desktop. Creating an easy log console is straightforward, using a floating div or another visual element to point out messages sent by a console.log call.
For example:
If (console==undefined) {
Var console = new Object();
Console.log = function(text) {
If (document.getElementById("console")==undefined) {
Document.getElementsByTagName("body")[0].innerHTML = "<div id='console'></div>";
}
Document.getElementById("console").innerHTML += "<p>" + text + "</p>";
}
}
With some CSS to the console and console p selectors, you'll see a console. With some scripts, you'll also create an object browser and a console JavaScript execution engine using eval.
Performance Optimization
Performance is that the key to mobile web success. People want high-performance websites. We hate to attend on our desktops, and therefore the situation is way worse on mobile devices, with their constrained resources. I could write an entire book about mobile web performance, except for now i will be able to just attempt to distill some best practices and share some hacks that you simply can easily apply to enhance your website’s performance.
Performance has recently become a hot topic within the desktop web world. Generally mobile web developers should follow an equivalent practices, but there are some new ones to stay in mind also , and a few desktop web best practices which will not work on these devices.
Mobile browsers aren’t an equivalent as desktop web browsers, and not all mobile browsers are created equal. Specifically, the number of resources which will be downloaded in parallel and therefore the cache functionality differ. Nevertheless, it's better to approach mobile performance optimization from here than from the bottom.
Measurement
The first thing we'd like to do is to measure. If we cannot measure, we cannot optimize. However, measuring mobile websites isn't easy. Typical desktop measurement and profiling tools don’t work for mobile devices, and HTTP sniffers are difficult to implement for mobile browsers.
Advanced memory and process profiling for JavaScript remains more of a dream than a reality. However, Yahoo! has created an easy JavaScript profiler called the Yahoo! UI Profiler work on any A-grade browser (Symbian, iPhone, Android), and you'll always use new Date().get Milliseconds() to get the time differences between two moments in your JavaScript code.
If you're using an emulator or a true device with WiFi capabilities, you'll use any HTTP sniffer proxy, configuring the emulator and your device together with your desktop IP address and port because the proxy for navigation. There are dozens of tools for doing this, but the one i prefer best is named the Charles Web Debugging Proxy.
The lifetime of a JavaScript programmer has changed radically since 2006, with the looks of Ajax and many libraries that help us work better with this language. Many of those libraries modify or add complete new behaviors to the language, creating new languages inside JavaScript.
If the libraries are supported JavaScript, and mobile browsers support JavaScript, why can we care? the solution is that a lot of those libraries believe some not clear things within the standard, and while they need been prepared and tested on desktop browsers (Internet Explorer, Firefox, Safari, Chrome, Opera), they need not been tested on all the mobile browsers.
That is the primary reason why we'd like to take care about using big JavaScript libraries. The second reason is that the impact on download and execution times. As mentioned earlier, these libraries modify the language and therefore the behavior of objects, and although we don’t use any of a library’s code, the library will got to load itself completely, which takes time. This will cause performance problems in some browsers, so we are getting to test the time that typical libraries want initialize themselves on mobile browsers.
Table shows the results for the jQuery, Prototype, Yahoo! UI, and Dojo libraries. Remember that execution time will depend tons on the hardware and CPU. These tests are just intended to form you aware of the average time that including a library can take.
Table. JavaScript libraries average execution/load times in seconds
The conclusion is that you simply should avoid these libraries if you'll . If you can't avoid them, use them just for smartphones, and remember that some features and plug-ins might not work properly.
A lot of developers have released alternative libraries that are geared for mobile devices and are lighter than the previous ones. There also are full frameworks for mobile application development like jQTouch, iUI, iWebKit, and Webapp.Net. These frameworks will take care of the visualization, events, and interaction of our websites. There also are other libraries which will replace jQuery and therefore the others on mobile devices. They're Very light libraries that provide basic DOM, event, and Ajax support.
A. BaseJS
BaseJS may be a lightweight library compatible with mobile Safari and other WebKitbased browsers. It's only been fully tested on Safari, from iOS 1.0 to 3.0. BaseJS provides a selector like jQuery’s, $(selector), and a few similar methods, like each, addClass, hasClass, removeClass, toggleClass, getXY, fire, and a few Ajax methods.
B. XUI
XUI may be a simple JavaScript framework for building mobile websites that takes up only 6.7 KB compressed. It's available for free of charge and has been fully tested on WebKit-based browsers and Opera Mobile. The developers are performing on adding support for IE Mobile and BlackBerry. XUI is almost like jQuery, but it's more powerful than baseJS. XUI uses x$ because the main selector object and includes the methods listed in Table.
Table. XUI common methods for a selector query
So, for example, we can capture an onclick for buttons with a class with the following code:
x$('input.button').on('click', function(e){ alert('Ouch!') });
Or with code like this, chaining the methods à la jQuery:
x$('input.button').click(function(e){ alert('Ouch!') })
.html('Press Me! ').css({color: 'blue'});
For Ajax, XUI provides global xhr and xhrjson functions to create requests with options.
There are dozens of JavaScript UI libraries for implementing rich controls. The great question is: do they work on mobile browsers?
• Yahoo! UI
• jQuery UI
• Sencha (formerly Ext JS)
• Microsoft Ajax Control Toolkit
• Google Web Toolkit
• Adobe Spry
Table. UI libraries compatibility table
A. Mobile-specific UI libraries
Many UI libraries have appeared on the market within the past few years to facilitate mobile RIA development. Most of them were designed for specific platforms, but with minor changes or incompatibilities many of them should work on any device. The browser with the foremost specific platform is mobile Safari, and much of libraries allow us to make rich applications emulating native control behaviors for iOS. Common UI libraries for iPhone include:
• iUI
• jQTouch and Sencha Touch
• iWebKit
• WebApp.Net
• ciUI
• Universal iPhone UI Kit:
• Magic Framework
• Safire
The only official Android libraries are WebApp.Net and Sencha Touch. The others work with Android, too, but there could also be some bugs in animations and effects. Symbian devices have a replacement library that's optimized for widgets but also works on browser-based documents for a few of the controls available. It's called the Guarana UI and may be a jQuery UI–based library for the Symbian WRT browser.
Figure. With simple code we can create iPhone-like experiences like the ones shown here, using iUI (left) or jQTouch (right).
1. IUI.
IUI was one among the primary libraries developed for iPhone-style application development. It had been developed by Joe Hewitt, member of the Facebook developer’s team and author of the favored Firefox plug-in FireBug.
IUI may be a very simple to use, nonintrusive JavaScript library, including CSS and assets that emulate the native iPhone application controls, animations, and application workflow.
The main features are:
• No JavaScript coding required
• Extends the behavior of standard HTML markup
• Overrides links and forms with Ajax requests
• Updates the page with smooth iPhone transitions with no code
The library uses the master-detail navigation method, copied from the UITableView control from Cocoa Touch. UITableView may be a native control in iPhone.
The main structure of an iUI website is simply an easy HTML file that has CSS and JavaScript files and contains a div for the highest toolbar and one ul for every “list page” we would like to show:
<!-- Leave this toolbar div with no changes -->
<div class="toolbar">
<h1 id="pageTitle"></h1>
<a id="backButton" class="button" href="#"></a>
</div>
<!-- This is the home screen -->
<ul id="home" title="Home Page" selected="true">
<li><a href="#first">First</a></li>
<li><a href="#second">Second</a></li>
<li><a href="#third">Third</a></li>
<li><a href="ajax.html">Loaded by AJAX</a></li>
<li><a href="more.html" target="_replace">More...</a></li>
</ul>
<ul id="first" title="Other Screen">
... Other options ...
</ul>
... Other pages
IUI uses the child element with selected="true" because the home screen when the page loads the first time, and each link with a hash (#) is a link to a different screen that loads on an equivalent page and is identified by the ID after the hash, à la WML card.
The toolbar is present and therefore the Back button works automatically, restoring the previous screen’s title and employing a smooth swipe animation to go back. To reference an external file, we use a traditional link: it'll load via Ajax and be inserted below the toolbar. The external file only have a ul or div element with none other root tag.
We can also implement an in-site pagination design pattern using target="_replace". This may load the href document using Ajax and insert its contents where the li with the replace link is defined. This document only have lis with none other root element, and it should end with another replace link if there are more elements to paginate.
Other advanced features that iUI supports include:
• Modal dialog pop-ups
• Form designs
• Emulation of native form controls
• Stripped tables
• Right toolbar button
2. JQTouch.
JQTouch is a jQuery plug-in for iPhone web development that produces similar results to iUI, but with more powerful graphics and animations. It's also unobtrusive, but it does require some JavaScript code to initialize the page.
With some visual differences, it also works on the Android and webOS browsers. The supported features include:
• Native WebKit animations using jQuery methods
• Callback events
• Flexible themes
• Swipe detection
• Extensions: floaty bar, geolocation, offline capability
• Visual controls
• Animations
To use jQTouch we'd like to first load jQuery 1.3.2 then the jQTouch script with two CSS files: the base file (jqtouch.min.css) and therefore the visual theme we would like to load. For example:
<script type="text/javascript" src="http://www.google.com/jsapi"></script>
<!-- We load jQuery using the Google AJAX API -->
<script type="text/javascript"> google.load("jquery", "1.3.2"); </script>
<script type="text/javascript" src="jqtouch/jqtouch.min.js"></script>
<style type="text/css" media="screen">@import "jqtouch/jqtouch.min.css";</style>
<style type="text/css" media="screen">@import "themes/jqt/theme.min.css";</style>
To initialize the page, we can use:
<script type="text/javascript">
$.jQTouch({
Icon: 'iphone-icon.png',
PreloadImages: [
'themes/jqt/img/chevron_white.png',
'themes/jqt/img/bg_row_select.gif',
'themes/jqt/img/back_button_clicked.png',
'themes/jqt/img/button_clicked.png'
]
});
</script>
As in iUI, the most markup is completed using top-level elements with ids and links with hashes for linking within the same document. For example:
<div id="home" class="current">
<div class="toolbar">
<h1>jQTouch</h1>
<a class="button slideup" id="infoButton" href="#about">About</a>
</div>
<ul class="rounded">
<li class="arrow"><a href="#ui">User Interface</a><small
Class="counter">4</small></li>
<li class="arrow"><a href="#animations">Animations</a><small
Class="counter">8</small></li>
<li class="arrow"><a href="#ajax">AJAX</a><small
Class="counter">3</small></li>
<li class="arrow"><a href="#callbacks">Callback Events</a><small
Class="counter">3</small></li>
<li class="arrow"><a href="#extensions">Extensions</a><small
Class="counter">4</small></li>
<li class="arrow"><a href="#demos">Demos</a><small
Class="counter">2</small></li>
</ul>
<h2>External Links</h2>
<ul class="rounded">
<li class="forward"><a href="http://www.jqtouch.com/"
Target="_blank">Homepage</a></li>
<li class="forward"><a href="http://www.twitter.com/jqtouch"
Target="_blank">Twitter</a></li>
<li class="forward"><a href="http://code.google.com/p/jqtouch/w/list"
Target="_blank">Google Code</a></li>
</ul>
</div>
3. Sencha Touch
It is a well-liked framework of Sencha for creating a user interface for mobile applications. It helps the developer create a mobile app using simple HTML, CSS, JS which supports many mobile devices like android, IOS, BlackBerry, and Windows. It's supported MVC architecture. The newest version of Sencha Touch is 2.4.
Features of Sencha Touch
Following are the foremost prominent features of Sencha Touch
• Customizable and quite 50 integrate UI widgets with a set of rich UI like lists, carousels, forms, menus, and toolbars, built specifically for mobile platforms.
• Code compatibility of latest versions with the older one.
• A flexible layout manager that helps organize the display of information and content across multiple mobile devices with different OS.
• The framework includes a robust data package which will consume data from any backend data source.
• Adaptive layouts, animations, and smooth scrolling for a far better mobile web application experience for the utilization .
• Out-of-the-box, native-looking themes for each major platform enables to form web and hybrid applications match the design and feel of the target platforms.
Benefits
Sencha Touch is that the leading standard for business-grade web application development. It offers the tools necessary to create robust applications for many of the mobile devices providing one platform for developing applications. Following are a number of the advantages
• Provides a responsive touch feature, hence the user can easily navigate while using the mobile app.
• Provides compatibility with all the newest versions of IOS, Android and Blackberry, and Windows.
• Provides fastest possible speed desirable for any mobile application.
• Provides a cost-effective solution with its cross-platform compatibility.
• Based on the native APIs and basic web development languages like HTML, CSS, JS which makes it easier for a developer to know Sencha Touch.
Limitations
Sencha Touch API doesn't have the subsequent capability
• The app doesn't have access to the device’s camera, contacts, and accelerometer.
• It doesn't provide the push notification facility. For this, we've to use websockets or long polling.
• According to general public license policy, it's free for open source applications however purchased commercial applications.
• It isn't good for hardcore graphics and animation apps like for gaming apps.
Tools
- Sencha SDK
This is Sencha development kit wont to create a skeleton of the project. We use the command "sencha -sdk path/to/touch generate app appName" to make an app with the name given within the command.
When the app is made , you'll see the subsequent files within the app
• app − This folder contains model, view, controller and store files for the app.
• app.js − this is often the most JS file for your application. From this file, the Sencha code flow starts.
• app.json − this is often the configuration file for the app, all the configuration details presents here.
• index.html − this is often the most html file where we include the app.js and other Sencha related files.
• package.json − This file has all the dependency and other information associated with the app.
• resources − This folder includes all the CSS files and images required for the application.
2. Sencha CMD
Sencha CMD may be a command line tool, which provides the features of Sencha Touch code minification, scaffolding, build generation, and other useful features for production purpose.
We use command "Sencha app build package" within the command prompt to create the application for this. Attend the app directory within the command prompt and kind the above command. Once the build is successful, we'll see the minified version of the application basically used for production purpose.
3. Sencha Inspector
Sencha Inspector is a debugging tool to debug any issue in Sencha code during development.
Environment
Local Environment Setup
This section guides you on the way to download and found out Sencha Touch on your machine. Follow the steps to set up the environment.
Downloading library files
Download a commercial version of Sencha Touch library files from the subsequent link https://www.sencha.com. You'll get the trial version from the site on your registered mail id, which can be a zipped folder named sencha-touch-2.4.2-commercial.
Unzip the folder and you'll find various JavaScript and CSS files add in your application. Include mostly the subsequent files
Javascript Files − JS file which you'll find under folder \sencha-touch-2.4.2commercial\touch-2.4.2 are −
Sr.No | File & Description |
1 | Sencha-touch.js This is the core file which consist of all functionalities to run the application. |
2 | Sencha-touch-all.js This file is with all the code minified with no comments in the file. |
3 | Sencha-touch-debug.js This is the unminified version of sencha-touch-all.js used for debugging purpose. |
4 | Sencha-touch-all-debug.js This file is also unminified and is used for development as it contains all the comments and console logs to check any errors/issues. |
You can add these files to your projects JS folder otherwise you can provide a direct path where the files reside in your system.
CSS Files − There are number of theme based files which you'll find under folder I:\sencha touch\sencha-touch-2.4.2-commercial\touch-2.4.2\resources\css\sencha-touch.css
These library files will be added in Sencha Touch application as follows
<html>
<head>
<scripttype="text/javascript"src="../sencha-touch-2.4.2-commercial/touch-2.4.2/sencha-touch-all.js"></script>
<linkhref="../sencha-touch-2.4.2-commercial/touch-2.4.2/resources/css/sencha-touch.css"rel="stylesheet"/>
<scripttype="text/javascript"src="app.js"></script>
</head>
</html>
You can keep Sencha Touch application code in app.js file.
CDN Setup
CDN is content delivery network with which you are doing not got to download the Sencha Touch library files, instead you'll directly add CDN link for ExtJS to your program as follows
<html>
<head>
<scripttype="text/javascript"src="https://cdn.sencha.com/touch/sencha-touch-2.4.2/sencha-touch-all.js"></script>
<linkhref="https://cdn.sencha.com/touch/sencha-touch-2.4.2/resources/css/sencha-touch.css"rel="stylesheet"/>
<scripttype="text/javascript"src="app.js"></script>
</head>
</html>
Popular Editors
As it may be a JavaScript framework used for developing web applications, the project will have HTML, JS files, and to write down your Ext JS programs, you'll need a text editor. There are multiple IDEs available within the market. Except for now, you'll consider one among the subsequent
• Notepad − On Windows machine, you'll use any simple text editor like Notepad, Notepad++.
• Brackets − Another popular IDE which may be downloaded from http://brackets.io/.
• Sublime − Another popular IDE which may be downloaded from https://www.sublimetext.com/3/.
Naming Convention
Naming convention is a set of rules to be followed for identifiers. It makes the code easily readable and understandable for other programmers also .
Naming convention in Sencha Touch follows the standard JavaScript convention, which isn't mandatory but an honest practice to follow. It should follow camel case syntax for naming the class, method, variable, and properties.
If the name is combined with two words, the second word will start with an uppercase letter always. For instance , doLayout(), StudentForm, firstName, etc.
Sr.No. | Name & Convention |
1 | Class Name It start with an uppercase letter, followed by camel case. For example, StudentClass |
2 | Method Name It should start with a lowercase letter, followed by camel case. For example, studentMethod() |
3 | Variable Name It should start with a lowercase letter, followed by camel case. For example, studentName |
4 | Constant Name It should be in uppercase only. For example, COUNT, MAX_VALUE |
5 | Property Name It should start with a lowercase letter, followed by camel case. For example, enableColumnResize = true |
Architecture
The bottom layer for any mobile application is OS, on top of that anything or everything is made . Then we've the browsers on which we'll be running the applications. It might be Chrome, Safari, IE anything. The upper layer may be a W3 standards, which is common for all. Sencha Touch stands or is made on top of W3 standards, which is nothing but HTML5, which makes one application compatible with different browsers of various devices.
Sencha Touch may be a combination of three frameworks as ExtJs, JqTouch, and Raphael. It follows MVC architecture. MVC separates the code into more manageable chunks.
Although the architecture isn't mandatory for the program, however, it's a best practice to follow this structure to form your code highly maintainable and organized.
Project Structure With Sencha Touch App
----------src
----------resources
-------------------CSS files
-------------------Images
----------JavaScript
--------------------AppFolder
-------------------------------Controller
------------------------------------Contoller.js
-------------------------------Model
------------------------------------Model.js
-------------------------------Store
------------------------------------Store.js
-------------------------------View
------------------------------------View.js
-------------------------------Utils
------------------------------------Utils.js
--------------------------------app.js
-----------HTML files
Sencha Touch app folder will reside in the JavaScript folder of your project.
The App will contain controller, view, model, store, and utility files with app.js.
App.js − The main file from where the flow of program will start. It was included in main HTML file using <script> tag. App calls the controller of application for remainder of the functionality.
Controller.js− it's the controller file of Sencha Touch MVC architecture. This contains all the control of the application, the events listeners, and most of the functionality of the code. It performs the subsequent tasks: routing, intermediate between view and model, and executes events.
View.js− It contains the interface a part of the application, which shows up to the user. Sencha Touch uses various UI rich views, which may be extended and customized consistent with the need .
Store.js− It contains the locally cached data, which is to be rendered on view with the help of model objects. Store fetches the info using proxies, which has the path defined for services to fetch the backend data.
Model.js− It contains the objects which binds the store data to view. It's the representation of the real-world object, which deals with the database.
Utils.js− it's not included in MVC architecture but it's a best practice to use this so on make the code clean, less complex, and more readable. We will write methods during this file and call them in controller or view renderer wherever required. It's helpful for code reusability purpose also .
MVC
MVC stands for Model View Controller. It's an architectural pattern which separates the application into logical components making it more manageable.
The following diagram shows how MVC architecture works
Controller− Controller controls whole application it notify view if model is modified and performs actions supported user inputs.
View− It contains the interface a part of the application which is visual to user. It notify controller to vary model on user input.
Model − It contains the objects which binds the store data to view. It's representation of the important world object which deals with database. It also notify controller for any change in view.
First Program
Following are the steps to write down the first Hello World program in Ext JS.
Step 1
Create an index.htm page in an editor of our choice. Include the specified library files within the head section of html page as follows.
Index.htm
<!DOCTYPE html>
<html>
<head>
<linkhref="https://cdn.sencha.com/touch/sencha-touch-2.4.2/resources/css/sencha-touch.css"rel="stylesheet"/>
<scripttype="text/javascript"src="https://cdn.sencha.com/touch/sencha-touch-2.4.2/sencha-touch-all.js">
</script>
<scripttype="text/javascript">
Ext.application({
Name:'Sencha', launch:function(){
Ext.create("Ext.tab.Panel",{
Fullscreen:true, items:[{
Title:'Home', iconCls:'home', html:'Welcome to sencha touch'
}]
});
}
});
</script>
</head>
<body>
</body>
</html>
Explanation
• Ext.application() method is that the starting point of Sencha Touch application. It creates a worldwide variable called 'Sencha' declared with the name property all the Application's classes like its Models, Views and Controllers will reside under this single namespace, which reduces the probabilities of colliding global variables and file names.
• launch() method is named once the page is prepared and every one the JavaScript files are loaded.
• Ext.create() method is employed to make an object in Sencha Touch. Here, we are creating an object of straightforward panel class Ext.tab.Panel.
• Ext.tab.Panel is that the predefined class in Sencha Touch for creating a panel.
• Every Sencha Touch class has different properties to perform some basic functionalities.
Ext.Panel class has various properties like
• fullscreen property is to form use of an entire screen, therefore the panel will take fullscreen space.
• items property is that the container for various items.
• iconCls is that the class used for displaying different icons.
• title property is to supply the title to the panel.
• html property is that the html content to be shown within the panel.
Step 2
Open the index.htm enter a standard browser and you'll get the subsequent output.
Builds
Today's demand for an internet application is to develop a fast application with less development efforts. Sencha Touch helps in doing so with ease because it provide variety of build libraries to settle on from, supported the event or production code with the power to make a custom build.
Sencha Touch build libraries loads the classes dynamically. Dynamic loading stands for the classes that gets loaded when required and only those classes are going to be added which are required within the application. This makes the application run faster because the number of files to be loaded reduces, simultaneously decreasing the time to load.
Sencha Touch 2.x provides the subsequent five build libraries.
Sr.No. | Builds & Usage |
1 | Sencha-touchdebug.js It is used for developing the application locally. It is a nonminified version with all comments and debug logs for easy debugging during development. |
2 | Senchatouch.js This file is used for production purpose. It is the minified version when we perform a custom build. |
3 | Sencha-touchall.js This file is used to perform production. It is the minified version when we don’t need custom build. |
4 | Sencha-touchall-debug.js This file is used for debugging in production. It is not minified and contains all the comments and debug logs. |
5 | Sencha-touchall-compat.js This build is used to migrate the version 1.x to version 2.x. It gives a warning when version 1.x code is not compatible and require the code modification. |
Advantages of Having a Custom Build
Custom build does not load all the touch files. It loads only those files, which we are using in the application, which makes the application faster and easily maintainable.
Sencha CMD is used to create a custom build. To create a custom build in Sencha CMD, go to the directory where the app file resides and type one of the following commands to create a build.
Sr.No. | Command & Usage |
1 | Sencha app build native Builds the app and prepares a file called as packager.temp.json which is used to package an application--the packager.temp.json is the same as packager.json, but contains extra paths. |
2 | Sencha app build -run native Builds and automatically packages the application, and launches the perticular simulator. |
3 | Sencha app build package Create the app with packaging support, but doesn’t configure a packager JSON file. This is useful for projects that manually maintain several packager.json files. |
Once the build is successful, it will generate all-classes.js file which we need to include in our index.html to make it production ready.
Following code shows the changes to be done for production ready code.
Index.html before building application
<!DOCTYPE html>
<html>
<head>
<linkhref="https://cdn.sencha.com/touch/sencha-touch-2.4.2/resources/css/sencha-touch.css"rel="stylesheet"/>
<scripttype="text/javascript"src="https://cdn.sencha.com/touch/sencha-touch-2.4.2/sencha-touch-debug.js"></script>
<scripttype="text/javascript"src="app.js"></script>
</head>
<body>
</body>
</html>
Index.html after building the application
<!DOCTYPE html>
<html>
<head>
<linkhref="https://cdn.sencha.com/touch/sencha-touch-2.4.2/resources/css/sencha-touch.css"rel="stylesheet"/>
<scripttype="text/javascript"src="https://cdn.sencha.com/touch/sencha-touch-2.4.2/sencha-touch.js"></script>
<scripttype="text/javascript"src="app.js"></script>
<scripttype="text/javascript"src="app-classes.js"></script>
</head>
<body>
</body>
</html>
4. JQuery Mobile
JQuery Mobile is a user interface framework, which is made on jQuery Core and used for developing responsive websites or applications that are accessible on mobile, tablet, and desktop devices. It uses the features of both jQuery and jQuery UI to supply API features for mobile web applications.
It was developed by the jQuery project team within the year 2010 and written in JavaScript.
Why Use jQuery Mobile?
• It creates web applications that it'll work an equivalent way on the mobile, tablet, and desktop devices.
• It is compatible with other frameworks like PhoneGap, Whitelight, etc.
• It provides a group of touch-friendly form inputs and UI widgets.
• The progressive enhancement brings a singular functionality to all or any mobile, tablet, and desktop platforms and adds efficient page loads and wider device support.
Features of jQuery Mobile
• It is made on jQuery Core and "write less, do more" UI framework.
• It is an open source framework, and cross-platform as cross-browser compatible.
• It is written in JavaScript and uses features of both jQuery and jQuery UI for building mobile-friendly sites.
• It integrates HTML5, CCS3, jQuery and jQuery UI into one framework for creating pages with minimal scripting.
• It includes Ajax navigation system that uses animated page transitions.
Advantages of jQuery Mobile
• It is easy to find out and develop applications if you've got knowledge of HTML5, CSS3 features.
• It is cross-platform and cross-browser compatible therefore you don’t need to worry about writing different code for every device resolution.
• You can create the custom theme using ThemeRoller without writing the road of code. It supports all HTML5 browsers.
• It uses HTML5 with JavaScript for straightforward development of web applications.
• It is made during a way that permits an equivalent code to automatically scale from the mobile screen to desktop screen.
Disadvantages of jQuery Mobile
• There are limited options for CSS themes, so sites can look similar which are built by these themes.
• Applications which are developed using jQuery Mobile are slower on mobiles.
• It becomes more time consuming once you combine jQuery mobile with other mobile frameworks.
• Difficult to supply complete customized visual design.
• All the features during a device can't be accessed by JavaScript during a browser.
Pages
The user interact with jQuery Mobile pages, which groups the content into logical views and page views. Page view is often animated using page transitions. Multiple pages are often created using HTML document and thus, there's no need of requesting the content from the server.
Following table demonstrates the types of pages in detail.
Sr.No. | Type & Description |
1 | Single Page A single page is created in HTML document with the help of a standard way of writing a template. |
2 | Multi-Page Template Multiple pages added in the single HTML document, which loads together by adding multiple divs with data-role = "page". |
3 | Dialogs Page Modal dialogs open content in an interactive overlay above the page. |
Conventions, not requirements
• The data-role attribute elements like the header, footer, page, and content are wont to provide the basic format and structure of a page.
• For single page documents, the page wrapper was required for auto-initialization is about as optional.
• The structural element is often excluded for a webpage with custom layout.
• To manage pages, the page wrapper is injected by the framework when it's not included by the markup.
Prefetching pages
Including the attribute data-prefetch, we will prefetch pages into the DOM within the single page templates. For more information click here.
DOM Cache
When the browser memory gets full in DOM, then some time downs the mobile browser or might crash thanks to loading of multiple pages. There's an easy method to stay the DOM tidy
• When a page is loaded via ajax, then it indicates to get rid of the page from DOM once you redirect to a different page.
• The previous page which you've visited are often retrived from the cache once you revisit it.
• Instead of removing the pages, you'll tell jQuery mobile to keep it in DOM by using the subsequent line
$.mobile.page.prototype.options.domCache =true;
• Set the domCache option as true on the page plugin to stay all the pages within the DOM, which was visited previously.
PageContainerElement.page({ domCache:true});
Icons
JQuery Mobile provides a set of built-in icons, which can be used with buttons, listview buttons which will make the buttons more attractive.
Following table lists down some of the icons used in the jQuery Mobile framework.
Sr.No. | Icon Area & Description |
1 | Icon Set It sets the icon in the button. |
2 | Positioning Icons It specifies the position of the icon in the button. |
3 | Icon-only It displays only an icon in the button. |
4 | Icon shadow It adds an icon shadow in your button. |
5 | Removing Circle It removes the grey circle around the icon. |
6 | Black or White Icons It changes the color of icons to black or white. |
7 | Combining alt and nodisc It combines the alt and nodisc classes to the icon. |
5. Enyo
It is an open source JavaScript framework for cross-platform mobile, desktop, TV and web applications emphasizing object-oriented encapsulation and modularity. It was developed by Palm, which was later acquired by Hewlett-Packard then released under an Apache 2.0 license. It's sponsored by LG Electronics and Hewlett-Packard.
Bootplate
Bootplate was simplified way of making an app, providing a skeleton of the program's folder tree. The Bootplate template provides an entire starter project that supports source control and cross-platform deployment out of the box. It are often wont to facilitate both the creation of a replacement project and therefore the preparation for its eventual deployment.
Libraries
• Layout: Fittables, scrollers, lists, drawers, panels.
• Onyx: supported the first styled of webOS/Touchpad design but available to be used on any platform.
• Moonstone: employed by LG SmartTV apps but available to be used on any platform.
• Spotlight: To support key-based interactions and "point and click" events on remote controls and keyboards.
• Mochi: Advanced interface library.
Enyo Mochi UI
It's maintained by the community since the team behind webOS released this abandoned interface from Palm/HP as open source. This library isn't included on bootplate immediately , but has excellent design documents.
• enyo-iLib: Internationalization and localization library, it wrap ilib's functionality on Enyo apps. G11n was another library that has been deprecated on newer versions of enyo.
• Canvas
• Extra
• enyo-cordova: Enyo-compatible library to automatically include platform-specific Cordova library (WIP).
Use
The following projects are built with Enyo:
• LG Smart TV apps.
• Openbravo Mobile and Web POS.
• xTuple ERP Web and Mobile App.
Partial list of Enyo apps are often found on Enyo Apps. Some developers are often found on Enyo Developer Directory.
Examples
This is an example of a 'Hello world program' in Enyo
Enyo.kind({
Name: "HelloWorld",
Kind: enyo.Control,
Content: 'Hello, World!',
});
New HelloWorld().write();
Supported platforms
In general, Enyo can meet all relatively modern, standards-based web environments, but due to the range of them there are three priority tiers. At 2015 some platforms supported are:
• Tier 1 Supported at high priority:
Packaged Apps: iOS7, iOS6 (PhoneGap), Android 4+ (PhoneGap), Windows 8.1 Store App and Windows Phone 8 (PhoneGap), Blackberry 10 (PhoneGap), Chrome Web Store App, LG webOS.
Desktop Browsers: Chrome (latest), Safari (latest MAC), Firefox (latest), IE11 IE10, IE9, IE8. (Win).
Mobile Browsers: iOS7, iOS6, Android 4+ Chrome, Kindle Fire and HD, Blackberry 10, IE11 (Windows 8.1),IE10 (Windows Phone 8).
• Tier 2 Supported
Packaged Apps: iOS5, iOS4, Android 2.3,Firefox OS, Tizen OS, Windows 8 Store App, Windows (Intel AppUp).
Desktop Browsers: Opera, Chrome >10, Firefox >4, Safari >5.
Mobile Browsers: iOS5, iOS4, Android 4+ Firefox, webOS 3.0.5, webOS 2.2, BlackBerry 6-7, BlackBerry Playbook et al.
• Tier 3 Partial support
Mobile Browsers: Windows Phone 7.5.
• No support
Desktop Browsers: IE8
Mobile Browsers: Windows Phone 7, BlackBerry 6, Symbian, Opera Mini
6. Montage
It is framework helps you to develop rich HTML5 applications that use JavaScript both on the front-end via the browser, and back-end via Node.js. Montage is meant to permit you to develop applications optimized for today and tomorrow’s range of connected devices.
You also build rich UIs within the client, and use a service-oriented back-end to handle data persistence and server-side logic. All using one language, and with the power to possess code reuse throughout the complete stack. Montage opens a replacement world of opportunity for web developers.
Features
- Components and HTML templates
- Bi-directional data binding
- Data persistence
- Serialization
- Event Management
Montage comes with the Skeleton theme. It is a basic, neutral-looking theme for HTML5 controls and inputs. You'll use it as a wireframe theme for prototypes, start line for creating your own theme, or easily style it with CSS to make custom skins. The Skeleton theme aims to supply cross-browser support so you'll use it as a fallback theme.
JavaScript Mobile UI Patterns
Mobile devices have had to develop alternate paths for handling common tasks.
Clear text box button
In their native UIs, touch devices have added a really nice feature to text boxes: the likelihood of clearing all the text by touching alittle X at the righthand side of the box. This is often especially useful due to the shortage of a keyboard. We will emulate this UI pattern easily by combining a picture and a touch JavaScript code.
Figure. You'll see this pattern implemented within the Yahoo! website for touch devices just like the iPhone.
To implement the clear button, we will use a 20×20-pixel image with the subsequent CSS style. The image are often shown as a div with a background image from the start , or only the user starts typing. It's important to feature a right padding to the input box therefore the X isn't overlapped by text:
<style type="text/css">
Div.clearx {
Background: transparent url('clearx.png') no-repeat right;
Height: 20px;
Width: 20px;
Margin-top: −26px;
Position: absolute;
Left: 235px;
}
Input.clearx {
Padding: 2px 40px 2px 10px;
Width: 200px;
Height: 24px;}
</style>
The HTML should look like this:
<input type="text" id="search" placeholder="Enter your search"
Class="clearx" />
<div class="clearx"
Onclick="document.getElementById('search').value =''"></div>
Autogrowing textarea
This UI pattern was created by the Google Mobile team and is currently used in Gmail. The problem is that if we have a large amount of text in a textarea, scrolling inside it is very painful in some browsers. The solution is to grow the textarea to fit the contents, so the user can use the normal page scrolling instead of the textarea’s.
We can capture the onkeyup event and grow the textarea if necessary. We also need to capture onchange, because pasting in iOS doesn’t generate an onkeyup event. The code, borrowed from the Google Code Blog with a few changes, is:
<script>
Var TEXTAREA_LINE_HEIGHT = 13;
Function grow(event) {
Var textarea = event.target;
Var newHeight = textarea.scrollHeight;
Var currentHeight = textarea.clientHeight;
If (newHeight > currentHeight) {
Textarea.style.height = newHeight + 5 * TEXTAREA_LINE_HEIGHT + 'px';
}
}
</script>
<textarea onkeyup="grow(event);" onchange="grow(event);">
</textarea>
Floating bar
Scrolling an outsized mobile page just to access a button or a link at the highest of the document are often very painful. A floating bar may be a great solution for avoiding this problem. A floating bar is simply a full toolbar, a menu, or a mix of both that always remains at the highest of the page when the user scrolls the content. It's not suitable for focus-based browsers, because there'll be usability issues when the user is tabbing between links.
For floating bars to figure , the browser must support the onscroll event. If the browser supports this event the toolbar moving are often done automatically, employing a smooth animation on some browsers. You'll decide whether to possess the floating bar appear at the start of the navigation or only after scrolling. The steps to make a floating bar are:
1. Create a div with the content of the floaty bar.
2. Define it as hidden off the screen with negative top values.
3. Define a WebKit transition animation.
4. Capture onscroll.
5. If the worth of window.scrollY (the top position of the scroll) is near zero, hide or move the div off the screen; if not, move the div to the scrollY position.
Cascading menu
A hierarchical menu is used for giant toolbars and just for touch devices. It also can be utilized in cursor-based browsers, but remember that in these browsers it's going to take the user a short time to urge the specified zone of the screen using the navigation keys. As these menus are used on touch devices, we should always not use mouseover events to open and shut the menu bar, and it's best to use onclick for both the opening and shutting actions.
We will also hide the menu when the user selects an option, scrolls the page, and moves the main target to a different object. An easy div show/hidden interaction with JavaScript will work, or you'll use a JavaScript library for this purpose.
Autocomplete
An autocomplete (or autosuggest) feature to scale back the user’s typing, just like the one in following Figure, may be a great feature, but it's not as simple to implement during a mobile site because it is during a desktop site. There are two sorts of autocompletes: preloaded and Ajax-based. The preloaded ones involve downloading all the possible values to suggest and storing them in JavaScript variables then , if offline storage is out there , storing them within the device for future usage.
Figure. Google.com autocomplete on an Android device
The first problem is that the issue of network latency and consumption. If the user is using 2G technologies (GPRS, EDGE), the latency for getting to the server or for preloading all the possible values are often long and dear . The second problem is that the UI design, for a couple of reasons: generating a floating div over other elements are often problematic in many mobile browsers, and browsing between suggestions in non-touch devices are often difficult.
All that aside, if we will save the users tons of typing, we'll be their heroes. So, the primary conclusion is that this solution is suggested just for touch-enabled smartphones, which we suppose are connected using WiFi or a 3G network. Next, we need to believe the planning . The advice isn't to use a floating div over other content, and instead to use a hidden div that replaces or pushes down the previous content. This div will appear slightly below the text box, and there must be an in depth button at the top-right corner.
Another thing to stay in mind for touch devices without QWERTY keyboards is that when the user has the main target within the text box, the virtual keyboard are going to be on the screen and there'll not be much space available. One solution which will make sure that the maximum amount space as possible is out there for the suggestion list is to scroll the document to the text box position when the user focuses within the text box. This may leave the text input just at the highest of the screen, and with the keyboard at rock bottom the center are going to be open for our suggestion list.
The fallback descriptor are need to specify a counter style to fall back to if the present counter style cannot create a marker representation for a specific counter value.
Syntax
/* Keyword values */
Fallback: lower-alpha;
Fallback: custom-gangnam-style;Description
If the required fallback style is unable to construct a representation, then its fallback style are going to be used. If a legitimate fallback style is not specified, it defaults to decimal.
A couple of scenarios where a fallback style used:
• When the range descriptor is specified for a counter style, the fallback style are going to be wont to represent values that fall outside the range.
• When the fixed system is employed and there aren't enough symbols to hide all the list items, the fallback style are going to be used for the remainder of the list items.
Formal definition
Related at-rule | @counter-style |
Initial value | Decimal |
Computed value | As specified |
Formal syntax
<counter-style-name>
Where
<counter-style-name> = <custom-ident>
Examples
Specifying a fallback counter style
HTML
<ul class="list">
<li>One</li>
<li>Two</li>
<li>Three</li>
<li>Four</li>
<li>Five</li>
</ul>
CSS
@counter-style fallback-example {
System: fixed; symbols: "\24B6""\24B7""\24B8";
Fallback: upper-alpha;
}
.list {
List-style: fallback-example;
}
Ajax
AJAX stands for Asynchronous JavaScript and XML. AJAX is a new technique for creating better, faster, and more interactive web applications with the assistance of XML, HTML, CSS, and JavaScript.
• Ajax uses XHTML for content, CSS for presentation, along with Document Object Model and JavaScript for dynamic content display.
• Conventional web applications transmit information to and from the sever using synchronous requests. It means you fill out a form, hit submit, and obtain directed to a replacement page with new information from the server.
• With AJAX, once you hit submit, JavaScript will make an invitation to the server, interpret the results, and update the present screen. Within the purest sense, the user would never know that anything was even transmitted to the server.
• XML is usually used because the format for receiving server data, although any format, including plain text, are often used.
• AJAX is a browser technology independent of web server software.
• A user can still use the appliance while the client program requests information from the server within the background.
• Intuitive and natural user interaction. Clicking is not required, mouse movement may be a sufficient event trigger.
• Data-driven as against page-driven.
Rich Internet Application Technology
AJAX is that the most viable Rich Internet Application (RIA) technology thus far . It's getting tremendous industry momentum and a number of other tool kit and frameworks are emerging. But at an equivalent time, AJAX has browser incompatibility and it's supported by JavaScript, it is tough to take care of and debug.
AJAX is based on Open Standards
AJAX is based on the following open standards such as
• Browser-based presentation using HTML and Cascading Style Sheets (CSS).
• Data is stored in XML format and fetched from the server.
• Behind-the-scenes data fetches using XMLHttpRequest objects in the browser.
• JavaScript to form everything happen.
AJAX can’t work independently. It's used in combination with other technologies to make interactive webpages.
JavaScript
• Loosely typed scripting language.
• JavaScript function is named when an occasion occurs during a page.
• Glue for the entire AJAX operation.
DOM
• API for accessing and manipulating structured documents.
• Represents the structure of XML and HTML documents.
CSS
• Allows for a transparent separation of the presentation style from the content and was changed programmatically by JavaScript
XMLHttpRequest
• JavaScript object that performs asynchronous interaction with the server.
Following is the list of web applications that make use of AJAX.
Google Maps
A user drag a entire map using the mouse, instead of clicking on a button.
• https://maps.google.com/
Google Suggest
As you type, Google offers suggestions. Use the arrow keys to navigate the results.
• https://www.google.com/webhp?complete=1&hl=en
Gmail
Gmail is a webmail built on the thought that emails are more intuitive, efficient, and useful.
• https://gmail.com/
Yahoo Maps (new)
Now it's even easier and more fun to urge where you're going!
• https://maps.yahoo.com/
Difference between AJAX and traditional CGI Program
Try these two examples one by one and you'll feel the difference. While trying AJAX example, there's no discontinuity and you get the response very quickly, but once you try the quality GCI example, you'd need to await the response and your page also gets refreshed.
All the available browsers can’t support AJAX. Following a list of major browsers that support AJAX.
• Mozilla Firefox 1.0 and above.
• Netscape version 7.1 and above.
• Apple Safari 1.2 and above.
• Microsoft Internet Explorer 5 and above.
• Konqueror.
• Opera 7.6 and above.
When you write next application then consider the browsers that don't support AJAX.
Steps of AJAX Operation
• A client event occurs.
• An XMLHttpRequest object is made .
• The XMLHttpRequest object is configured.
• The XMLHttpRequest object makes an asynchronous request to the Webserver.
• The Webserver returns the result containing XML document.
• The XMLHttpRequest object calls the callback() function and processes the result.
• The HTML DOM is updated.
Consider the following steps one by one.
A Client Event Occurs
• A JavaScript function is named because the results of an occasion .
• Example − validate "text" size = "20" id = ""id">.
The XMLHttpRequest Object is Created
Var ajaxRequest;// The variable that makes Ajax possible!
Function ajaxFunction(){
Try{
// Opera 8.0+, Firefox, Safari
AjaxRequest =newXMLHttpRequest();
}catch(e){
// Internet Explorer Browsers
Try{
AjaxRequest =newActiveXObject("Msxml2.XMLHTTP");
}catch(e){
Try{
AjaxRequest =newActiveXObject("Microsoft.XMLHTTP");
}catch(e){
// Something went wrong
Alert("Your browser broke!");
Returnfalse;
}
}
}
}
The XMLHttpRequest Object is Configured
In this step, we can write a function which is triggered by the client event and a callback function processRequest() will be registered.
Function validateUserId(){
AjaxFunction();
// Here processRequest() is the callback function.
AjaxRequest.onreadystatechange = processRequest;
If(!target) target = document.getElementById("userid");
Var url ="validate?id="+ escape(target.value);
AjaxRequest.open("GET", url,true);
AjaxRequest.send(null);
}
Making Asynchronous Request to the Webserver
Source code is available in above format of code. Code written in bold typeface is responsible to make a request to the webserver. This is performed using the XMLHttpRequest object ajaxRequest.
Function validateUserId(){
AjaxFunction();
// Here processRequest() is the callback function.
AjaxRequest.onreadystatechange = processRequest;
If(!target) target = document.getElementById("userid");
Var url ="validate?id = "+ escape(target.value);
AjaxRequest.open("GET", url,true);
AjaxRequest.send(null);
}
Consider that you enter Zara in the userid box, then in above request, the URL is set to "validate?id = Zara".
Web server Returns the Result Containing XML Document
You also implement your server-side script in any other language and its logic as follows.
- Get a request from the client.
- Parse the input from the client.
- Do required processing.
- Send the output to the client.
If we consider that you are going to write a servlet, then following is the code.
Publicvoid doGet(HttpServletRequest request,
HttpServletResponse response)throwsIOException,ServletException{
String targetId = request.getParameter("id");
If((targetId !=null)&&!accounts.containsKey(targetId.trim())){
Response.setContentType("text/xml");
Response.setHeader("Cache-Control","no-cache");
Response.getWriter().write("<valid>true</valid>");
}else{
Response.setContentType("text/xml");
Response.setHeader("Cache-Control","no-cache");
Response.getWriter().write("<valid>false</valid>");
}
}
Callback Function processRequest() is Called
The XMLHttpRequest object was configured to call the processRequest() function when there is a state change to the readyState of the XMLHttpRequest object. Now this function receives the result from the server and performs the required processing. In following example, it sets a variable message on true or false depends on the returned value from the Webserver.
Function processRequest(){
If(req.readyState ==4){
If(req.status ==200){
Var message =...;
...
}
The HTML DOM is Updated
This is the last step and in this your HTML page was updated. It performed in the following method
- JavaScript has a reference to any element in a page using DOM API.
- The particular way to gain a reference to an element is to call.
Document.getElementById("userIdMessage"),
// where "userIdMessage" is the ID attribute
// of an element appearing in the HTML document
- JavaScript is used to modify the element's attributes and element's style properties; or add, remove, or modify the child elements. Consider following example
<scripttype="text/javascript">
<!--
Function setMessageUsingDOM(message){
Var userMessageElement = document.getElementById("userIdMessage");
Var messageText;
If(message =="false"){
UserMessageElement.style.color ="red";
MessageText ="Invalid User Id";
}else{
UserMessageElement.style.color ="green";
MessageText ="Valid User Id";
}
Var messageBody = document.createTextNode(messageText);
If(userMessageElement.childNodes[0]){
UserMessageElement.replaceChild(messageBody, userMessageElement.childNodes[0]);
}else{
UserMessageElement.appendChild(messageBody);
}
}
-->
</script>
<body>
<divid="userIdMessage"><div>
</body>
Reference Text Book
1. Jeff McWherter, Scott Gowell, Professional Mobile Application Development, John Wiley & Sons, Ref: www.it-ebooks.org
2. Maximiliano Firtman, Programming the mobile Web, Oreilly, 2nd Edition, 2013, ISBN: 978-1-449-33497-0