Coding javascript for mobile browsers

54 179 0
Coding javascript for mobile browsers

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

Thông tin tài liệu

Tài liệu này dành cho sinh viên, giáo viên khối ngành công nghệ thông tin tham khảo và có những bài học bổ ích hơn, bổ trợ cho việc tìm kiếm tài liệu, giáo án, giáo trình, bài giảng các môn học khối ngành công nghệ thông tin

http://mscerts.net Coding JavaScript for Mobile Browsers First of all, let’s see what is happening with basic JavaScript compatibility (variables, functions and basic alert functionality) with mobile browsers. Table 1 illustrates the current levels of support on the different platforms. Table 1. JavaScript support compatibility table Browser/platform JavaScript support Safari Yes Android browser Yes Symbian/S60 Yes Nokia Series 40 Yes webOS Yes BlackBerry Yes from 3.8 Can be disabled by the user or the company; in that case, noscript is executed NetFront Yes Openwave (Myriad) Not available in Openwave; yes in Myriad Browser V7 Internet Explorer Yes Motorola Internet Browser Yes Opera Mobile Yes Opera Mini Yes, but everything after the onload script will be executed on the server, generating a postback Note: As Openwave does not support JavaScript and Myriad 7 is not commonly found on mobile devices today (making testing difficult), Openwave/Myriad will be left out of the following JavaScript-related tables. http://mscerts.net 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. Note: For old non-JavaScript mobile browsers or for browsers with JavaScript disabled, we can use the noscript tag. Only those browsers will display its content. When we talk about mobile JavaScript, we are talking about the same 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 many of them also accept not defining the language at all (using script alone): <script type="text/javascript"> // Code goes here </script> <script src="mysource.js" type="text/javascript"> Note: ECMAScript Mobile Profile defines two new types for the script tag, application/ecmascript and text/ecmascript, as the preferred types to use for ESMP-compatible code. Beyond that, text/javascript is the recommendation for XHTML MP documents and is the most compatible type to use for non-MP browsers. My recommendation is to carry on using the well-known text/javascript. 1. Code Execution 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 http://mscerts.net Bookmarklets A bookmarklet is a bookmark in the browser containing some JavaScript code using a javascript:protocol URL. When the user activates the bookmark, the JavaScript code is executed over the current document. This allows us to execute a wide range of testing, debugging, and other features over any web page. There are bookmarklets on the Web that are large applications, encoded in a single line of JavaScript. One of my favorites for desktop usage is Readability (http://lab.arc90.com/experiments/readability). The main problem with bookmarklets in mobile devices is how to add them. In the desktop web, the main way is to drag a link with the JavaScript code to the bookmarks area. This cannot be done in a mobile device, though, so bookmarklets are only useful if you can manage or synchronize them from a desktop (e.g., via iTunes for iPhone). There are a lot of bookmarklets for iPhone on the Web, including some that will show the source code of the page inside the mobile browser. These are only really useful for testing or debugging purposes, though, or for “only geek” features. Table 2 shows which of these work with which browsers. Table 2. Script execution compatibility table Browser/platform Script Event handler URL Safari Yes Yes Yes Android browser Yes Yes Yes Symbian/S60 Yes Yes Yes Nokia Series 40 Yes No before 6 th edition Yes webOS Yes Yes Yes BlackBerry Yes No before 4.6 Yes NetFront Yes Yes Yes Internet Explorer Yes Partial Yes Motorola Internet Browser Yes No Yes Opera Mobile Yes Yes Yes Opera Mini Yes No No http://mscerts.net Note: If a device is not compatible with JavaScript (different from a device that is compatible but has JavaScript disabled), it will show the JavaScript code to the user as text. We can avoid this problem by inserting an HTML comment just after the script tag: <script type="text/javascript"> <! // JavaScript code here > </script> 2. JavaScript Mobile Compatibility As you move into JavaScript on the mobile web, you’ll want to test compatibility and use some old- fashioned features. 2.1. Feature detection The simplest way to detect if a feature, API, function, or object is available to use is to ask if it exists using a simple if statement: if (object) { // Object available } For example: if (document.getElementById) { // DOM function available } Warning: Even on JavaScript-compatible devices, a script might not work because of the user’s (or company’s) profile. For example, BlackBerry devices have the option to disallow JavaScript from the browser or from the company policies. You should always present a non-JavaScript version of your site’s functionality. http:// m 2.2. St a JavaScr i being re p website s Figur e The list o • a • c • p • p • f The find on the m and a b a search f e The prin t are com p to use t h compati b m scerts.net a ndard dial o i pt supports a p laced by D y s , though, as e 1. Using s t o f available d a lert, for sho w c onfirm, for r p rompt, for r e p rint, for sen f ind, for invo k dialog isn’t r m arket. This d a ckwards Bo o e ature. t dialog isn’t p atible with a h em when n e b le than usin o gs a list of stan d y namic HTM L shown inFi g t andard Ja v usin d ialogs is: w ing a mes s r eceiving a B e ceiving a st ding the we b k ing the find r eally part of d ialog receiv e o lean. In ge n mobile com p a lmost every e eded. Using g any other s d ard dialogs L or UI librar i g ure 1. v aScript dia l g UI contro l s age oolean resp o ring from th e b page to the feature of th e the standar d e s three opti o n eral, it shou l p atible, for o b JavaScript- e a standard d s olution for t h that are und e i es. They m a l ogs you wil ls f r om the o o nse from th e e user printe r e browse r d , but it work s o nal parame t l d be avoide d b vious reaso e nabled mo b d ialog will al w h e same tas k e rvalued in m a ke great sta l get free ri c o perating s y e use r s in almost e v t ers: the text d in mobile b ns, but the a b ile phone (a s w ays be qui c k . m odern desk t ndard dialog c h and mul t y stem. v ery non-IE d to find, a ca b rowsers. M o lert, confirm, s Table 3 sh o c ker, simpler, t op websites s for use in m t iplatform in t d esktop web se-sensitive o st of them d o and prompt o ws). I enco u nicer, and m , often m obile t erfaces, browser Boolean, o n’t have a dialogs u rage you m ore http://mscerts.net Table 3. Standard dialog support compatibility table Browser/platform alert, confirm, prompt Safari Yes Android browser Yes Symbian/S60 Yes Nokia Series 40 Yes webOS Yes BlackBerry Yes NetFront Yes Internet Explorer Yes Motorola Internet Browser Yes Opera Mobile Yes Opera Mini Yes, rendered on the server Common problems with the alert dialog (and the others) are the usage of the carriage return for multiline text, and how to display text that’s too big to fit in the available space. For the first problem, it is common in desktop JavaScript to use the \n (newline) escape special character. (There are other special escape characters, too, like \tfor tabulation.) Let’s see what happens with both problems in mobile browsers. Table 8-4 reports on their support for newlines and large amounts of text in dialogs, and Figure 2 shows the use of a scrolling area that supports long text. http:// m Figu r Browse Safari A ndroid Symbia n Nokia S e webOS BlackBe NetFron t Internet Motorol a Opera M Opera M m scerts.net r e 2. On so m Tab l r/platform browser n /S60 e ries 40 rry t Explore r a Internet Br o M obile M ini m e browse r l e 4. Multipl \n i n Ye s Ye s Ye s Ye s No, Ye s Ye s Ye s o wser Ye s Ye s Ye s r s, big alert s t o e lines and n alerts s s s s shows one l s s s s s s s have scrol o uch devic e scrolling te x Scroll Yes, c Scroll Scroll Scroll l ine No, te x Scroll A utos c Scroll Scroll Scroll Scroll lbars (or c a e s). x t in alerts c in g suppor t hange alert a x t overflow s c c roll a n be scroll e c ompatibilit y t for lon g te x a ppearance w c reen witho u e d with a fin y table x t w ith scroll s u u t scroll ger, on u pport http://mscerts.net Note: For usability reasons, if a device has a numeric keyboard it is best to use a normal text input with numeric capabilities, rather than a selection list. Remember that a numeric keyboard is useful for numeric entries. 2.3. Writing to the document The document.write function allows us to dynamically write HTML code to a document while it is rendering. This was a very common technique in the ’90s, but there are a lot of reasons for not using it in modern websites. Today, the preferred technique is to manipulate the document using DOM after the onload event. Note: If your script doesn’t use document.write, you should use the script attribute defer="defer". This will tell compatible browsers that they shouldn’t wait for the script to download and/or execute to continue rendering the document. That said, in the mobile space sometimes it is better not to deal with DOM (especially in low-end devices), so performing document.write operations can avoid a lot of problems. As Table 5 shows, this technique still works on a lot of browsers. Table 5. document.write compatibility table Browser/platform document.write support Safari Yes Android browser Yes Symbian/S60 Yes Nokia Series 40 Before 6 th edition, no after onload support webOS Yes BlackBerry Before 4.6, no after onload support NetFront Yes Internet Explorer Yes Motorola Internet Browser Yes, no after onload support http://mscerts.net Table 5. document.write compatibility table Browser/platform document.write support Opera Mobile Yes Opera Mini Server rendering For example, you can create a year selection list dynamically to save bytes in the original document. For rendering performance purposes, it is better to use document.write with all the HTML at the same time (including the beginning, contents, and end of a tag) rather than partially writing a tag with many lines. The following code demonstrates this technique: <!DOCTYPE html PUBLIC "-//WAPFORUM//DTD XHTML Mobile 1.0//EN" "http://www.wapforum.org/DTD/xhtml-mobile10.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <title>Document Write</title> <script type="text/javascript"> function createNumericSelect(name, from, to) { var html = "<select name='" + name + "'>"; for (var i=from; i<to; i++) { html += "<option>" + i + "</option>"; } html += "</select>"; document.write(html); } </script> </head> <body> <form action="send"> <script type="text/javascript"> createNumericSelect('year', 1990, 2020); </script> </form> </body> </html> Remember that document.write should not be used in an event handler, like onload or onclick, because it will have unpleasant results. If you need to dynamically generate content on the page, it is better to use DOM than document.write. http://mscerts.net 2.4. Platform detection JavaScript has a native navigator object representing the client browser on which the code is running. We can use this technique to detect what device our code is running on and make a decision based upon that. Note: When using a for, remember to define the index variable as a local file with var i=initial_value. If not, you’ll be using a global variable, which can have some performance and bug issues. The navigator object has many properties, but the most 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 will use the string’s indexOf function to verify whether some of these attributes have the values we are looking for. For example: // Detects if it is an Android device var android = (navigator.platform.indexOf("android")>=0); if (android) { // Do something } Table 6 shows what is returned from these properties for each browser. In this table, assume that <User A gent> will be replaced with each device’s user agent ID. Table 6. JavaScript navigator object properties compatibility table Browser/ Platform appName appVersion mimeTypes platform Safari Netscape 5.0 (<User Agent>) Array iPhone, iPod, or iPad Android browser Netscape 5.0 (<User Agent>) Array null Symbian/S60 Netscape 5.0 (<User Agent>) Array S60 Nokia Series 40 before 6 th edition Nokia Empty string Undefined Undefined Nokia Series 40 6 th edition Netscape 2.0 Undefined Nokia_Series_40 [...]... unique form DOM Level 2 added some new methods, and it is the most commonly used version today for mobile browsers DOM Level 3 added events, validation, and XPath support, but it’s not compatible with most mobile browsers 3.2 Browsing Table 14 shows compatibility for DOM browsing methods in the different mobile browsers http://mscerts.net Table 14 DOM support compatibility table Browser/ platform DOM... compatibility table Browser/platform Support for appendChild and removeChild Safari Yes Android browser Yes Symbian/S60 Yes Nokia Series 40 No before 6th edition webOS Yes BlackBerry No before 4.6 NetFront Yes Internet Explorer Yes Motorola Internet Browser No Opera Mobile Yes Opera Mini Yes Warning: For the best mobile performance, use innerHTML instead of using DOM methods for adding, moving, and removing... Internet Explorer Yes Motorola Internet Browser Yes Opera Mobile Yes Opera Mini Yes, reload causes a new history entry 2.7 Manipulating windows One of the most popular (and annoying) features of JavaScript is the usage of window.open for opening the classic popup windows For mobile browsers, the usage of this technique is not ideal, for many reasons Many browsers can’t open multiple windows (although Figure... Browser/platform Cookie management Motorola Internet Browser Yes Opera Mobile Yes Opera Mini Yes 3 DOM The Document Object Model is an increasingly common part of mobile development 3.1 Versions Two main DOM versions are available for mobile browsers: • • DOM Level 1 HTML DOM Level 2 HTML & Core DOM Level 1 has been deprecated as a standard, but it still works in desktop and some mobile browsers I remember... Internet Browser No Opera Mobile Yes Opera Mini No Timers in background Continue working Continue working Note: The Gmail for Mobile team discovered some issues with timer behavior on mobile Safari and Android devices, and made the results public in the team blog at http://www.mobilexweb.com/go/timers The conclusions are: for low-frequency timers (1 second or more), there are no performance issues, and... compatibility table Browser/platform Support for preloading images Safari Yes Android browser Yes http://mscerts.net Table 18 Preloading images compatibility table Browser/platform Support for preloading images Symbian/S60 Yes Nokia Series 40 No before 6th edition webOS Yes BlackBerry No before 4.6 NetFront Yes Internet Explorer Yes Motorola Internet Browser No Opera Mobile Yes Opera Mini Yes 3.7 Adding... most helpful usage is for form input controls The behavior varies on different mobile browsers On some touch devices, focusing in a text box should automatically open the onscreen keyboard, and in some cursor-based browsers it will position the cursor over the element Note: If the document the user is browsing is form-based, like a search page or a contact us page, it will be better for usability to automatically... using the jQuery JavaScript library, and it is included natively as an extension in some WebKit-based browsers and Firefox 3.5 for desktop At the time of this writing query selectors are covered in a W3C draft known as Selectors API Level 1 A query is made using document.querySelector(selector) for unique results, or document.querySelectorAll(selector )for many possible return values For example: var... image Table 16 shows which browsers support changing properties dynamically Table 16 Changing properties dynamically compatibility table Browser/platform Support for changing properties Safari Yes Android browser Yes Symbian/S60 Yes Nokia Series 40 No before 6th edition webOS Yes BlackBerry No before 4.6 NetFront Yes Internet Explorer Partial Motorola Internet Browser Yes Opera Mobile Yes Opera Mini Yes... simpler innerText) For example, you may want to use it to replace content in or add content to an element Table 17 shows which browsers currently support this property http://mscerts.net Table 17 innerHTML property compatibility table Browser/platform Support for innerHTML Safari Yes Android browser Yes Symbian/S60 Yes Nokia Series 40 No before 6th edition webOS Yes BlackBerry No before 4.6 NetFront . rendering an XHTML file or JavaScript code. Note: For old non -JavaScript mobile browsers or for browsers with JavaScript disabled, we can use the noscript tag. Only those browsers will display. http://mscerts.net Coding JavaScript for Mobile Browsers First of all, let’s see what is happening with basic JavaScript compatibility (variables, functions and basic alert functionality) with mobile browsers. . <script type="text /javascript& quot;> <! // JavaScript code here > </script> 2. JavaScript Mobile Compatibility As you move into JavaScript on the mobile web, you’ll want

Ngày đăng: 22/10/2014, 22:15

Tài liệu cùng người dùng

  • Đang cập nhật ...

Tài liệu liên quan