Introduction to Wireless Web Development
Wireless Web development is Web development based on the browser on smart phones. Now smart phones mainly have Android and IOS two operating systems, so the development based on mobile Web is mainly based on Android and IOS two operating systems on the Web development.
Common ground for Web development based on both operating systems:
- Both browser engines are based on WebKit, so Web development based on mobile is mainly based on WebKit browser development, for other browsers, such as Firefox, IE, Opera and other browsers, can not do compatibility considerations.
- Both are developed according to the HTML5 specification, so they have good support for HTML5 features.
Difference:
- Android manufacturers are seriously fragmented, and due to the open source features of WebKit, there are many modified versions of WebKit browsers on the market. Manufacturers will modify webKit according to their own needs, leading to serious fragmentation of HTML5 features. At the same time, different manufacturers of THE HTML5 standard implement different, resulting in different support for HTML5 features. Take input Type =date date control as an example, some manufacturers have implemented the standard, some manufacturers have not implemented the standard, even if the manufacturers have implemented the standard, for the display of date control, interaction is not the same.
- Android version fragmentation. Until the writing of this document, Android has developed to version 4.4. For Web development, it is mainly divided into two stages: 2.X and 4.X. It was specially customized by Google for the performance of mobile phones at that time. Because the hardware performance of mobile phones at that time was not very good, the implementation of WebKit viewer of 533 version was a simplified version, so the implementation of HTML5 standard brick was not very thorough, and some implementations also made specific reservations. This series of releases can be divided into 2.2 and below and 2.3. For 2.2 and below, html5 support is not very good, and even if it is implemented, there are some problems with the implementation of certain details. 2.3 was a leap forward, with the porting of chrome’s core code implementation for PC, so android web development has begun a new journey since 2.3.
- Because ios is closed and Apple implements it strictly in accordance with THE HTML5 specification, the HTML5 specification is well implemented on ios.
- The standard implementation of IOS and Android for HTML5 is different in interface layer and interaction layer. For example, the type date control of ios and Android are completely different in interaction implementation. Although they are implemented according to w3c standards. This is also something to be aware of in everyday Web development.
Mobile phone related
Before talking about specific mobile Web development, we need to talk about the characteristics of the mobile phone, the characteristics of the mobile phone affects a lot of mobile Web development, so before talking about language money, we need to understand the characteristics of the mobile phone.
Mobile phone performance
Smart phones have developed in the past two years, and their hardware has developed rapidly. However, no matter how many pieces of hardware are developed, due to the characteristics of mobile phones, performance and functions are a balance point. Because you don’t want to use a machine that works super well, but the phone is very hot and only lasts an hour. So in many ways, performance on mobile phones is limited. The part of the Web that is affected by this, called native, is much larger. Therefore, Web is not a compiled language and can only be run dynamically on mobile phones. In addition, webKit core occupies a large memory and is a single process and single thread application, which is more affected by CPU and memory.
Page rendering
The performance of mobile Web development is greatly affected by the page rendering problem, while the performance of JS script is no longer prominent, which is mainly due to the use of v8 engine on Android, which greatly improves the performance of script execution. This is not the case on PCS, where page rendering performance is extremely high due to high-performance hardware and powerful graphics cards. On mobile, however, the limited hardware capabilities, coupled with the lack of dedicated display hardware such as a graphics card, leave all page rendering to the CPU. This, combined with the CPU’s limited execution frequency, results in slow page rendering. So on mobile, you’ll find that when there are a lot of render changes on the page, there will be a lag phenomenon. Such as long list sliding, page switching animation and so on. These conditions limit what HTML5 can do, and therefore require more care when it comes to dynamic change.
The keyboard
The keyboard is also different from the PC, in the first mobile Web development, will often forget. Because mobile phones now use soft keyboards, they become part of the page at some point. The keyboard is a very special device, especially because different phones have different implementations of the keyboard and HTML layout. The following aspects illustrate the characteristics of mobile phone keyboard:
-
Keyboard layout Because the mobile phone interface is very small, so the keyboard will take up a large part of the mobile phone screen, for the impact of the keyboard on the HTML page layout, if you have never done, may not notice that Android and ios processing, android manufacturers are different ways to deal with the way. When ios pushes the keyboard from below, if the input control is above the keyboard height after the page is pushed, the keyboard pops up in a floating layer and pushes the triggered control above the keyboard. If the control is at the bottom of the page, and if the pushed keyboard overlays the control, the system pushes the entire page up until the control is pushed above the keyboard. And the implementation of Android is different, there are some Android implementation and ios, some Android models implementation is different, if the trigger of the input control than the height of the bottom of the keyboard, will automatically increase the height of the entire Document, increase to the height of the control over the height of the keyboard. Two problems arise due to different implementations,
- For some JS simulation popover types, this can cause positioning problems. A classic case is the reminder of toast. The toast will appear at the bottom of the phone, usually using the fixed attribute. If the whole document is pushed up according to ios, there will be no problem, but if the whole document is dynamically raised, If the position is not good, the toast will appear in the middle of the keyboard. Since the keyboard is in the upper layer of the browser, it is impossible to overlay the positioned elements on the keyboard through z-index. The solution is to monitor the events of all controls when toast appears, and dynamically calculate the current position and reset it when focus appears.
- If the triggered input is in an overly complex layout, some Android computers will have calculation errors when calculating the actual position of the input, especially with advanced features such as TRasnlate set through CSS. I have encountered a machine that, due to calculation errors, when the keyboard is up, The input box is not stretched over the keyboard and is completely covered by the keyboard, causing input problems. Therefore, due to the existence of various nasty Android phones, the input may not be embedded in the complex hierarchy, with more complex CSS position attributes, so as not to cause calculation errors.
-
There are various types of keyboards on mobile phones, the more commonly used keyboards are full keyboard, numeric keyboard, symbol keyboard, email keyboard, search keyboard, amount keyboard, telephone keyboard and so on. However, due to the limitations of the Web, what can be really used is very limited and implemented differently on ios and Android. And the type of keyboard that pops up is the same. This is described in detail in the input below, so it will not be repeated. In a word, the keyboard up, completely dependent on the system and manufacturer’s implementation. The type of keyboard cannot be customized.
- Keyboard events up and down the keyboard. This is also a very difficult question. Before ios6, when the control gets focus, if it is not triggered by the user, the keyboard will not pop up. After ios6, there is a property that can do this. On Android, as long as it is not triggered by the user, the event cannot be triggered. There is no solution yet. The keyboard can be closed by js blur.
Page scrolling
-webkit-overflow-scrolling is a popular scrolling feature, but on native phones, local scrolling is not supported. After ios5, there is a CSS property that supports partial scrolling (-webkit-overflow-scrolling) : Touch attribute, but there are certain defects, in some scrolling, will be invalid, so it is recommended not to use.
There is a very specific rule about the need for pages, because this has a direct impact on web development. This is when the browser locks the render on the page for performance reasons when the page is inertial sliding (finger loose sliding). In other words, it is not valid for js to dynamically modify elements while the page is sliding. Until scrolling stops, this is a very special rule. It exists on IOS and Android, and it stands out on IOS. This feature is necessary for daily evaluation, because it makes it impossible to implement certain functions in sliding, such as fixing an element to a position from a static programming state, or state transitions. When sliding, even if js is set dynamically, the page does not respond until the scroll ends. Therefore, many effects of touch control in Native are not perfectly realized on the Web.
Note: for ios rolling system implementation details you can refer to this address: www.iunbug.com/archives/20…
The other problem with scrolling is that on ios, even if the page is headed, you can continue to pull up. There is a force feedback effect, and it can’t be undone. It looks cool and beautiful. However, in actual projects, it is almost impossible to use this beautiful effect. On the contrary, it will cause a strange feeling, especially when webApp is made, when a complete interface has navigation head, it can still be pulled up, which is a very strange feeling for users. And the scroll is system implementation, there is no way to remove, so judging a web or native app, can be judged in this way, close up, pull up again, if you can online, and there is not a refresh, but a default background of the ios, it is the web, but on the other hand is not necessarily the native, Because scrolling can be disabled on the Web directly, simulated scrolling can be implemented via CSS3 or JS, but this kind of scrolling can cause serious performance problems, especially for scrolling over long pages.
The modal window
Modal window is also a very common function in projects. Modal window can be called by JS alert and confirm, etc. However, there is a problem with moving modal window, that is, the current URL address will appear in the head of modal window and cannot be removed, which is unacceptable in the eyes of interaction. Therefore, modal Windows are rarely used in actual scenarios. You need to be careful when evaluating projects in the future.
HTML
The most common problem encountered in the head header in wireless Web development is the setup of the ViewPort
For the Settings above, you can Google, there is a very detailed description, I am not too repeated here, there are several addresses below, you can make a reference to developer.mozilla.org/en-US/docs/… Developer.apple.com/library/saf… In fact, more specific, you can use OverStackFlow or Google to query.
Best practices:
- In general, in the head of all wireless pages, to add the setting of the viewport, if not added to this value, will cause in some WebKit browsers, browsers will be based on their own judgment, do their own zoom, zoom, etc., resulting in pages can not be accessed normally, In particular, some apps embed webKit visitors to visit, will occur above the situation, so to ensure that you said that the design of the web page display consistent across all phones, add this setting
- In the viewport Settings numerical generally don’t need to change, because now the numerical already meet most of the project, will appear in the very specific pages, of course, requires the user to manually zoom operation, but if you change the value, need a detailed test on different phones, otherwise there will be things happen outside of your expectations.
HTML5 tag usage
In the development of wireless Web, we will often use HTML5 tag, for most of the HTML5 tag will not encounter problems, such as nav, footer, article and other tags, these display tags are generally safe to use. Caniuse.com/ is recommended if you are not sure if an HTML5 tag is usable.
The input tag
This type of tag is very special, because it is the type of tag that interacts most closely with users, and it is also the type of tag that has the most problems. The biggest difference between IOS and Android in HTML5 tags is the input type tag, and the implementation of the input type on different Android devices is also very different, and different types of input will pop up different keyboard types, especially IOS. Generally in the development process often encounter the need to pop up the keyboard requirements, the following can be done for reference. One of the most important features of these controls is that the interactive interface is realized by the browser, which can not be customized through CSS and HTML. Therefore, we must be very careful about the daily review of interactive and visual requirements. There may be more than a comma, which cannot be modified. Here are some types of insurance:
- Text: Text This type indicates that the input box is a text message. Full keyboards are displayed on both Android and ios devices.
- Passsword: The password is used differently on a mobile phone and a PC. Note this
- Button, checkbox, Radio, reset, submit and other controls can be used, but it needs to be noted that on Android and ios phones, the control style will be different, if you want to fully control the style, Reset -webkit-appearance: None and set the style you want.
Types to be used with caution:
- Email, search, tel, URL, etc. These tags have the same appearance as text, except that search has rounded corners. The main difference is the keyboard that pops up. For ios, the HTML5 specification supports it well, so it almost always pops up the keyboard that it specified. Unfortunately, there is no money type, so you can’t pop up the Money keyboard on ios. For Android is more sad, due to various manufacturers for HTML5 specification support is not unified, resulting in for the above type, the pop-up keyboard is different from different models.
- File is a very special type tag. For ios, it already implements File, but it now only invoks files that are in the photo set. In ios7, it also implements photo and video files, but there is a bug in 7.0.3 that causes the application to blink back. For Android, if the browser is used, the file selection of the file type will evoke the browser implementation of the file selection, but the file selection varies from phone to phone, the specific implementation is different, the Web can not control. If you use WebKit in android app, you need android WebKit private API interface to realize file selection upload, which you can view through Google.
- Date type, this is also a very common control in mobile web development, for the use of this control, need to pay attention to, on the ios platform, due to the large-scale flat design of ios7, so in ios7 and the previous system, the pop-up control interface and interaction is different, this need to pay attention to, And the date type is not implemented in ios3. Android for date date control implementation is very fragmented, generally speaking, 4.X, big manufacturers of mobile phone browser implementation is better.
- Range, color, Month, Datetime, time, and week are not recommended due to platform and mobile phone restrictions.
JS custom control issues
Because of the above problems, often will receive this kind of demand, is very eager to complete implementation, a control on the PC, because of the development for many years, the mechanism is relatively complete, can use js to simulate the implementation, but in the mobile terminal, due to the factors such as cell phones, platform, use js to simulate a control is not a good idea. Various experiences show that the use of JS to simulate the control, in some models and platforms will appear very strange and unsolvable problems. So for JS custom controls, unless you have a very big grasp, otherwise do not easily touch
CSS3
Mobile browser support for CSS3 is generally good, but due to the fragmentation of Android, mobile fragmentation and various versions of IOS, there are many areas that need to be carefully operated.
If you’re talking about mobile Web CSS, you need to talk about the CSS properties of the -webkit- prefix. These prefixes are specifically browser properties for the WebKit core, and probably many of the -WebKit – properties are already successful generic properties that don’t need to be prefixed. In order to be compatible with older browsers, the -webkit- prefix is required
CSS3 has many types, which can be roughly divided into the following types: layout type, render type, selector type, animation type.
CSS reset
Before we talk about the layout above, we need to talk about the reset problem of CSS. This problem dates back to the HTML4 era, when it was very difficult to unify a style across platforms due to various browsers, standards and default styles for various HTML tags on PCS. Hence reset, which resets the default styles of all HTML tags to make it easier to create pages on all platforms. Entering the era of wireless Web, there is a lot of debate about whether reset should exist. There are two groups: the reset group and the Normalize group. The Reset group believes that even in the mobile era, there are still various fragmentation issues that need to be reset, while normalize believes that in the wireless Web, many specifications have received support from many vendors, most notably Google and Apple, so there is no need to reset. You just need to unify those labels.
Therefore, in the market for mobile development, there are two CSS modes, reset mode and Normalize mode. Personally, there is no absolute good or bad between them. It depends on the nature of the project.
- Reset mode is suitable for strict requirements that all platforms must be completely in accordance with a unified form of the development of the project, generally speaking, for the type of WebApp project, may use reset more suitable. Reset mode is also suitable for WRITING UI controls, because UI controls have strict standards, using Reset, you can better precise control.
- Normalize Mode This mode applies to Web – featured websites. A Web – featured website refers to a website that is suitable for various platforms and needs to experience the features of each platform. There is no need to force all platforms to unify.
However, for most projects, common product managers and interactions require a unified product performance across platforms, so in real projects, reset may be used more often.
The layout type
Layout type CSS means that these properties affect the way the HTML is laid out. HTML4 is the most classic to position, float and other highly used properties, for its use, it is estimated that countless documents have been, I will not repeat here. One layout type is described below: Flex. In the past, the horizontal layout was probably the most painful for front-end developers. After the table layout was abandoned, div layouts became popular, and float layouts were widely used. However, float layouts also had their own pain point, which was to implement float in different browsers. In particular, 6 and 7 in IE series have very strange performance and need a lot of trick to ensure no problem. Entering the mobile age, you can use Flex layout.
flex
You can Google the layout of Flex, which is not described here, but the way flex is used is everywhere, and what I’m talking about here are the implicit rules.
- Display: box display: flexbox display: box display: flexbox Flex, for Android and ios, uses box. The following is the compatibility of different versions of Flex for reference. For more information, see this document.
Chrome | Safari | firefox | Opera | IE | Android | iOS |
---|---|---|---|---|---|---|
21+ (modern) 20- (old) | 3.1 + (old) | 2-21 (old) 22+ (new) | 12.1 + (modern) | 10+ (hybrid) | 2.1 + (old) | 3.2 + (old) |
- Flex properties used in mobile terminal using flex, use less as far as possible attributes, because not all mobile phones are all attributes of the flex is achieved, so at the time of use, suggest only use the flex this attribute, this property is basic to satisfy the demand for the vast majority of the scene, for a variety of other properties, if must use, I suggest doing a stackOverflow and Google search to determine that it has no compatibility issues.
- Flex layout limitations. Current flex can’t satisfy all the layout of the demand, demand for the following layout, flex is insatiable, layout is described below, list of multiple projects, each project in average level with the width of the screen, and the width of each project is fixed, if multiple projects and more than the width of the screen, automatically, beyond the project down to the next line, Proceed horizontally from left to right. This layout, which used float, works, but with float you can’t do a horizontal project and average the screen width. For the layout above, the interface now uses a float layout, plus a responsive layout, plus a percentage width for each item in a different width setting, with elements in the item horizontally centered.
fixed
Fixed layout can be said to be used on the PC is very much a property, using fixed property on the phone, need to be very careful. The following two platforms are specifically described:
- Fixed in ios system officially began to support the layout of fixed after ios5. Before ios5, Apple did not implement it for the consideration of performance. Therefore, when using fixed, you need to pay attention to the project you are working on that supports the lowest version of ios version. Fixed attribute began to support, in the actual use, there are still many small holes in the foreign special page to say ios fixed problem. Provide the following address, reference: remysharp.com/2012/05/24/… . It is safer to keep the structure as simple as possible in a fixed layout and avoid overly complex layouts. Generally, fixed attributes can be used for the head and tail of app.
- Android system after 2.1, has begun to support fixed, but due to the different manufacturers for fixed implementation, 2.1 and 2.2 for fixed support is not very good, there will be flashing, disappear, displacement and other rendering problems when scrolling. After 2.3, fixed issues are relatively few, but there are various rendering issues on individual phones. From 4.x onwards, Fixed performed better. Therefore, if fixed effect is needed on Android, its effect needs to be comprehensively evaluated.
Before and after
Before and after are probably the most commonly used CSS properties. Its specific meaning, can refer to a variety of documents, not detailed here. This is a general usage scenario. Before and after were originally defined by the W3C as inserting content before and after a node, so the content attribute and value must be included in before and after. But in a real project, it automatically inserts a node before and after the node, usually not a text, but an absolutely positioned icon or something like that. While this implementation can be done by adding a structure to HTML, inserting before and after nodes has the advantage of making HTML structure more concise and semantic. The inconvenience, however, is troubleshooting the problem, so you can’t see the before and after element types directly by looking at the HTML structure. However, the modern browser with the debugger tool, can be viewed, the problem is not very big. So these two pseudo-classes are recommended.
Apply colours to a drawing type
Render type refers to the main function of this type is to render THE HTML structure, say a little more commonly, is to add various colors, sizes on the structure. You can say that a large part of CSS does all of these things. Render types can be divided into many different types depending on the perspective, but the following is the dimensional distinction between 2D and 3D.
2 d rendering
Most CSS properties are rendered in 2D. Due to the addition of a large number of useful 2D rendering properties in CSS3, the effects previously needed to use images to achieve, now through CSS Settings can also be achieved, the following mainly describes the more commonly used properties, as well as the use of attention points.
- Border-radius Rounded corner type This is a very common CSS type, almost in all projects more or less will use, before HTML4 era, the implementation of rounded corners is a very difficult thing, CSS3 attributes can be a good solution to the problem of rounded corners. However, when using rounded corners in practice, it is important to note that on ios, the implementation is quite perfect. On Android, it should be noted that on many models, the rendering of rounded corners does not reach an ideal state, especially for the connection between rounded corners and straight lines. It is not obvious when the radius of rounded corners is set relatively small (1-3 pixels). However, when exceeding 4 pixels, on some models, there will be obvious rounded edges and a direct difference of half a pixel. If the radius is very large (>10px), the rounded corners will be very jagged. Therefore, for rounded corners with a large radius, border-image is recommended instead of border-radius.
- Box-shadow box model shadow, this property is generally not too big a problem, so far no serious problems have been found, can be relatively safe to use. However, some lower-end Android devices do not support box-shadow, which needs to be paid attention to, but it is not a problem, because most of the box shadow is not particularly obvious, users generally do not pay attention to it.
- Text shadow is basically supported on mobile Web and can be used, but there is one thing that needs to be noted. In Android 2.3 and earlier versions, when blur radious is 0, text shadow will be invalid, which needs to be noted.
- Linear-gradient is not a property of CSS itself, but the value below the property, which is generally used in background properties. It is important to pay attention to the use of linear gradient. There are many ways to express linear gradient, and it varies with different mobile phones and versions. -webkit-gradient(Linear, left Top, left bottom, from(), to()))
- In daily use, border-image is a very useful attribute, and its main purpose is to stretch images. The specific usage method can be searched on the Internet. It is estimated that there will be such a problem: if an image is stretched to a certain width, There will be distortion in the image of the four corners. This is found on some Android phones, but not many, but it should be noted.
3 d rendering
3D rendering is a very cool attribute, it can 3D render the elements on the page, to achieve a variety of very cool effects. However, due to its very advanced, so can support 3D attributes of the model, version, manufacturers will also have a lot of different. So when I say 3D, I’m not going to use the properties in 3D, I’m going to use the properties.
From a practical point of view, the biggest benefit of 3D is its use of hardware acceleration, although it may be difficult to use its various properties directly, but it gives us a lot of hardware acceleration support. Therefore, when doing page animation, even if it is not a 3D change, it can turn on the hardware acceleration function through 3D Settings. Use the translateZ (0); Hardware acceleration can be enabled on the current node without any rendering changes. A lot of people here would think that using 2D animation would enable hardware acceleration, but it’s not, you have to use 3D to enable hardware acceleration, so be aware of that
Selector type
CSS3 provides a large number of new selectors, making the selection of a node becomes very simple, CSS3 selector many, most of the mobile phone are supported, but for daily project development, the following types will be very common, we can do reference, for other selectors, can refer to the Internet.
The first child, the last child
This is also a very common pseudo-class, especially in layout. A very classic scenario is a list that requires rounded corners at the top of a list item and below the next list item. Previously, if we needed to implement it, we needed to add an extra class to implement it. If you use these pseudo-classes, it’s very simple.
Property selector
In many CSS selectors, property selector is a very useful type, a more common scenario is the input style modification, so the input property is rich, for a specific type of input style modification, if through the previous way, only by adding the name of the class. With property selectors now in use, the amount of code and complexity is greatly reduced.
Animation types
Animation type is a more useful type in CSS3, it can realize the animation effect of nodes, with JS, can make its animation become very rich. However, when it comes to using animations correctly, you need to be careful, and the most important thing is performance.
Many performance issues that don’t exist on a PC become very obvious once they are on the phone. One of them is animation. Animation is performance-intensive due to the DOM nature of web pages, and web pages are single-process, single-threaded, so all applications run in a SINGLE UI thread. Performance on mobile phones has not yet reached the level of performance on PCS, so the performance issues of animation on mobile phones stand out.
Even if there are multiple cpus, only one CPU can be used at the same time. If the performance is to be thoroughly improved, a possible solution is to use Webworker to establish multi-threaded mode. Not many phones support Webworker, however. So near-stage performance is always a pain in animation.
But do not be too pessimistic, nor can not be used, but in use, need to be careful, can be from the following standards (no absolutely no certain, see the actual effect)
- The reflow triggered by the animation should be as small as possible
- Animation is absolute if possible
- The animation area should be as small as possible, and the structure inside should be simple
- Text is less expensive to animate, images are less expensive, and complex structures (e.g., HTML nested n-tier structures that contain complex layouts like float, Flex, etc.) are the most expensive.
- 3D animation is not recommended, and implementations vary widely from vendor to vendor
- It is not recommended to animate the entire page, such as simulating the full-page switching effect of Native
- Animation as far as possible using CSS instead of JS, if use JS, it is recommended to use webkitRequestAnimationFrame (if support), specifically how to use, please Google by yourself
- For animated nodes, turn on hardware acceleration translateZ(0)
- Animation time should not be too long, experience shows that 500ms-1S, about the same, the longer the time, the more obvious its performance problems
The above is the point of attention before use, if it has been determined that there is no problem, then start to enter the topic. In general, 2D animations use the following two properties: Transition and animation.
- Transition works well on mobile web platforms, but requires a WebKit prefix to ensure compatibility on older models. Transition can animate CSS properties like width, height, color, and background. If you are not sure, you can set it to all.
If set to auto, animation changes will be weird. It is recommended that animation start with a specific pixel or percentage. If the background changes are pictures, the effect of picture switching is not very ideal. Avoid changing different pictures, but you can consider using background position to change the position.
- Animation is compatible with all mobile browsers, but in earlier versions it needs to be prefixed with -webkit. Animation is suitable for animations that need to be triggered repeatedly.
From a practical point of view, the scenes used by Transition and animation are different. Transition is suitable for short and small animations, while animation is suitable for repeated scenes. There are a few things to be aware of when using animated animations:
- Animation does not necessarily trigger, in some Settings of CSS, you will find that animation cannot be implemented, especially when fast switching, you will find that the animation is set to be forced to skip
- The phenomenon of broken frames in animation, that is, the animation card, is generally broken for the following reasons
- During an animation, garbage collection takes place and the entire page is forced to pause for hundreds of milliseconds. There’s nothing you can do about this because the page has no control over garbage collection, so don’t animate too long or the chances of encounters become high
- Multiple animations occur. Due to the single thread, when an animation is playing, if another animation appears, the current animation rendering will be suspended. Therefore, it is not suitable for multiple places to appear different animations in the same period of time
- During the animation playback, JS operations occur, which generally occurs before JS in the way of setTimeout or setInterval to conduct asynchronous programs, especially in ajax scenarios. Imagine that loading icon will appear when Ajax gets data. When remote data arrives, JS will perform many operations, such as data formatting, template combination, and rendering part of the page. All of these will affect the animation of Loading.
- It can also be caused by something happening to the system while the animation is happening, or by other background applications in the phone suddenly using a lot of CPU time. However, as the performance of the mobile phone improves, the incidence will decrease.
- Animation takes preparation time, which may sound crazy, but it does, and on a PC, because the hardware is so powerful, it takes very little preparation time, but on a phone, it’s a different world. For a simple example, if you make a rotation of an element by 45 degrees, the usual way to do this is to add the initialization class to the element, for example, the Angle is initialized to 0, and then you add the end class, which is an Angle of 45 degrees. Because of the transition setting, the rendering engine automatically changes the rotation from 0 degrees to 45 degrees. But on some phones this element happens, no animation, suddenly jumps to 45 degrees. The reason for this is that the browser engine needs to initialize this element when it is initialized to 0 degrees with JS, which is very short, but it takes time, say 10ms. If you add the closing class immediately after the js statement, if this statement takes only 8ms, it means that the latter class has arrived before the viewer animates the previous element. At this point, the CSS is forced to be set to the closing property. Therefore, when using animation, the end of the class will be artificially added by setTimeout tens of ms later. Specific dozens of ms to see the animation of the time.
- Both transition and animation are defined by the W3C to trigger an event at the end of an animation, but sometimes this event is not triggered. In practice, it may not be triggered in the following situations:
- The current node animation is not finished, another animation is set immediately, the previous animation end event sometimes disappears, for unknown reasons
- If the current node animates because the preparation time is too long and the end property is set, the end of the animation event will not be triggered
- If other events, such as garbage collection, occur during the animation and take longer than the animation time, the end-of-animation event may not occur
To sum up, be careful when using animation on the mobile Web.
Javascript
ES5 standard
Smart phones have better js support and better ES5 specification support. However, considering version compatibility issues, here are some methods that have been tested in practice:
- JSON object JSON object can be said to be the most frequently used object, in the PC era, due to browser compatibility problems, often refer to the JOSN class library, but in the webkit era, except for ios3.1, other versions have supported JSON object, ios3.1, It is estimated that there is only a very small market, so it can be considered negligible. So JSON native objects can be used directly on your phone.
- Array methods such as forEach, Indexof, every, Reduce, etc. can be used safely in mobile Web development
- Object Es5 Object methods are rarely used and do not have much feedback on compatibility. Therefore, caution is recommended
- Date Now is a new method, but not supported by all system versions. It is recommended to use it with caution. GetTime can be used instead
DOM selector
HTML 5 for our DOM selector provides a very good, is the document. The querySelector and document querySelectorAll these two methods, the two methods after make the + and ios +, can use, It takes a CSS selector as an argument. In real Web development, there is a large part of the work of DOM manipulation, through this artifact, can solve most of the DOM manipulation. I suggest you use these two methods more often.
Other DOM selectors are not compatible and should not be used.
Zepto
There is also a lightweight class library tool on the Web phone, that is Zepto. Many of its API interfaces remain compatible with the jquery interface. Its size is very small, and the gZIP package is around 10K, which is ideal for loading in the wireless environment of the mobile phone. The API address is zeptojs.com/
Click’s 300ms latency response
Speaking of mobile development, we have to mention the click incident, which is the most commonly called thing on mobile phones is the slow response of the click. Here’s the thing: in the early days of mobile phones, browsers had system-level zooming in and out functionality that would trigger site zooming in and out after the user clicked twice on the screen. But because the system needs to determine the user after clicking, have the next click the second time, so when the user clicks on the first, will be forced to wait for 300 ms, wait for the user at this time, if there is a user for the second time to submit, if not, will the click event, otherwise it will trigger a larger/smaller effect.
There is no problem with this design originally, but in the vast majority of mobile phone operations, the probability of user click events is much greater than that of double click, so all user clicks have to wait 300ms to trigger click events, resulting in slow response to users, which is difficult to solve. The common solution in the industry is to do tap yourself via touch events instead of Click. However, tap events have the following problems in practice.
The good news is that after chrome21.0, if you click on viewport width=device-width and disable zooming. this will remove the 300ms mandatory wait time, which will greatly improve the web response time. There is no such message on ios yet. But that’s going to take a while.
Mobile event
Javascript has a lot of user interaction related events, and there are some mobile specific events that you might encounter in your daily development. Here are some of the features of these events:
- Orientationchange is an event that occurs when the device is rotated. This can be very useful in some situations.
- Touchstart, TouchMove, TouchEnd, and TouchCancel are all supported on the mobile Web. Through these two events, a variety of user gestures can be simulated. However, due to the complexity of their processing, tap events may be simulated most. Many Web mobile libraries have the implementation of TAP events, but in practice, TAP is not well handled, the main problem of TAP, there are two, one is tap and scroll triggered at the same time, often trigger TAP events, the second is the sensitivity of tap, often trigger tap errors.
- Scroll event The trigger time of this event on PC is different from that on mobile phone. On mobile phone, scroll event will happen only when scrolling stops. Therefore, this event is seldom used on mobile terminal, because the trigger time is already too late. For functions that need to change the structure of a page on the move, Scroll can’t do it.
Basic knowledge of
Meta tags, these meta tags play a very important role in webApp development
The first meta tag says: Enforce a 1:1 document width to the width of the device, a maximum document width ratio of 1.0, and don’t allow users to click on the screen to zoom in. In particular, multiple properties in the content must be separated by a semicolon + space, and will not work if they are not specified.
Note that according to public_00, content is delimited by a semicolon, which is supported in older browsers but not the norm.
The specification should be comma separated by Safari HTML Reference-supported Meta Tags and Android – Supporting Different Screens in Web Apps
Among them:
- Width-viewport width
- Height-viewport specifies the height of the viewport
- Initial-scale – The initial scaling scale
- Minimum-scale – The minimum scale to which the user is allowed to scale
- Maximum-scale – The maximum scale to which the user is allowed to scale
- User-scalable – Whether the user can scale manually
The second meta tag is safari’s private meta tag on iPhone, which says: Allow full-screen browsing; The third meta tag, also private to iPhone, specifies the style of the status bar at the top of Safari on iPhone. The fourth meta tag tells the device to ignore the number on the page as a phone number
After setting initial-scale=1, we were finally able to design the page in a 1:1 ratio. One other important concept about viewPort is that safari on the iPhone doesn’t have a scrollbar at all, and it doesn’t simply “hide the scrollbar,” it doesn’t have it at all. The iPhone’s Safari browser actually displays the entire web page from the start, and then uses viewPort to view portions of it. When you drag with your finger, you’re not actually dragging a page, you’re dragging a viewport. It’s not just the scrollbars that are changing browser behavior. Interactive events are also different from the normal desktop. (Please refer to the JS series at your fingertips)
More detailed viewport-related knowledge is also available
This pixel is not that pixel
Mobile development events
Mobile browser commonly used gestures monitor encapsulation
Gesture events
- Touchstart // Triggered when a finger touches the screen
- Touchmove // Triggered when the finger already touching the screen starts to move
- Touchend // Triggered when the finger leaves the screen
- touchcancel
Touch events
- Gesturestart // Triggered when two fingers touch the screen
- Gesturechange // Triggered when two fingers touch the screen and start to move
- gestureend
Screen rotation event
Detect when the finger touching the screen changes direction
Related properties supported by touch events
- touches
- targetTouches
- changedTouches
- // X margin of touch relative to the viewport (Excludes scroll offset)
- ClientY // Y coordinate of touch relative to the viewport (Excludes scroll offset)
- ScreenX // Relative to the screen
- ScreenY // Relative to the screen
- PageX // Relative to the full page (includes scrolling)
- PageY // Relative to the full page (includes scrolling)
- Target // Node the touch Event originated from
- Identifier // An identifying number, unique to each touch event
- Screen rotation event: onOrientationChange
Check whether the screen is rotated
Function orientationChange() {switch(window.orientation) {case 0: alert(" screen.width: "+ screen.width + "; screen-height:" + screen.height); break; Case-90: alert(" screen-width: "+ screen-.width + "; screen-height:" + screen.height); break; Word-wrap: break-word! Important; "> < span style =" max-width: 100%; screen-height:" + screen.height); break; Case 180: alert(" width: "+ screen.width + "; Screen - height: "+ screen height); break; }; };
Adding Event Listeners
addEventListener('load', function(){ orientationChange(); window.onorientationchange = orientationChange; });
Finger sliding event:
// addEventListener('load',function(){window.onmouseWheel = twoFingerScroll; }, false // compatible with all browsers, indicating that the event handler is called in the bubbling phase (true capture phase); function twoFingerScroll(ev) { var delta =ev.wheelDelta/120; // Determine the value of delta (such as positive or negative) and return true; };
JS click delay
The click event is not a great experience with a 300ms delay due to waiting for click confirmation.
Instead of click events, developers mostly use wrapped TAP events, which consist of the TouchStart event + TouchMove judgment + TouchEnd event.
Creating Fast Buttons for Mobile Web Applications
Eliminate 300ms delay on click events in mobile Safari
WebKit CSS:
Ctrip UED compiled Webkit CSS documents, comprehensive, easy to query, common attributes below.
① “box model” of the specific descriptive nature of the surrounding box block content, including the boundary, filling and so on.
-webkit-border-bottom-left-radius: radius; -webkit-border-top-left-radius: horizontal_radius vertical_radius; -webkit-border-radius: radius; // webkit-box-sizing: sizing_model; Border constant value: border-box/ content-box-webkit-box-shadow: hoff voff blur color; // Container shadow (horizontal X offset; Offset in the vertical Y direction; Gaussian fuzzy radius value; Webkit-margin-bottom-collapse: collapse_behavior; Constant values: the collapse/discard/separate - its margin - start: width; -webkit-padding-start: width; -webkit-border-image: url(borderimg.gif) 25 25 25 25 round/stretch round/stretch; -webkit-appearance: push-button; // Built-in CSS representation, for now only push-button support
② the “visual formatting model” describes the nature and determines the position and size of the block elements.
direction: rtl unicode-bidi: bidi-override; Constants: bidi - override/embed/normal
③ “Visual effects” describes the properties of the adjusted visual effects block content, including overflow behavior, adjustment behavior, visibility, animation, transformation, and transition.
clip: rect(10px, 5px, 10px, 5px) resize: auto; Constants: auto/both horizontal/none/vertical visibility: visible; Opacity /hidden/visible -webkit-transition: opacity 1s linear; Ease /linear/ease-in/ease-out/ ease-in-out-webkit-backface-visibility: visibler; ease/linear/ease-in/ease-out/ease-in-out -webkit-backface-visibility: visibler; Constants: visible(default)/ hidden-webkit-box-reflect: right 1px; Reflect: webkit-box-reflect: Below 4px -webkit-gradient(linear, left top, left bottom, from(transparent), color-stop(0.5, transparent), to(white)); Webkit-mask-image: -webkit-gradient(linear, left top, left bottom, from(rgba(0,0,0,1)), to(rgba(0,0,0,0))); //CSS mask/mask effect -webkit-mask-attachment: fixed; Constant: fixed/ scroll-webkit-perspective: value; Constants: None (default) -webkit-perspective-origin: left top; -webkit-transform: rotate(5deg); -webkit-transform-style: preserve-3d; Constants: flat/preserve - 3 d; (2 d and 3 d)
The “generated content, auto-numbered, and listed” description property allows you to change a component of content, create auto-numbered chapters and headings, and manipulate the content of a style list.
Content: "Item" counter(section) "; This resets the counter. First section >two section three section counter-increment: section 1; counter-reset: section;
⑤ “paging media” describes properties of performance and appearance that control the behavior of printed versions of web pages, such as paging breaks.
page-break-after: auto; Constants: always/auto/get/left/right page break - before: auto; Constants: always/auto/get/left/right page break - inside: auto; Constants: auto/get
⑥ “Color and background” description attributes control the context of block-level elements and color text content components.
-webkit-background-clip: content; Constants: border/content/padding/text - its background - origin: padding. Constants: border/content/padding/text - its background - size: 55 px; Constants: length/length_x/length_y
⑦ “font” is a factor in the selection of specific descriptive character fonts. The report also describes properties used to download font definitions.
unicode-range: U+00-FF, U+980-9FF;
⑧ “Text” describes attributes of the specific text style, spacing and auto scroll.
text-shadow: #00FFFC 10px 10px 5px; text-transform: capitalize; Constants: capitalize/lowercase/none/uppercase word - wrap: break - word; Constant: break-word/ normal-webkit-marquee: right large infinite normal 10s; Constant: direction(direction) increment(repetition) style(speed) -webkit-marquee-direction: ahead/auto/backwards/down/forwards/left/reverse/right/up -webkit-marquee-incrementt: 1-n/infinite(infinite) -webkit-marquee-speed: fast/normal/slow -webkit-marquee-style: alternate/none/scroll/slide -webkit-text-fill-color: #ff6600; Constants: capitalize, capitalize, None, upperCase-webkit-text-Security: Circle; Constant: circle/disc/ None/square-webkit-text-size-adjust: none; Constants: auto/none; -webkit-text-stroke: 15px #fff; -webkit-line-break: after-white-space; Normal/after-white-space-webkit-appearance: caps-lock-indicator; -webkit-nbsp-mode: space; Constant: normal/ space-webkit-rtL-ordering: logical; Constants: Visual/logical-webkit-user-drag: element; Constants: element/auto/ none-webkit-user-modify: read-only; Constants: read-write-plaintext-only/read-write/read-only -webkit-user-select: text; Constants: text/auto/none
⑨ table describes the layout and design of the performance table.
-webkit-border-horizontal-spacing: 2px; -webkit-border-vertical-spacing: 2px; -webkit-column-break-after: right; Constants: always/auto/get/left/right - its - column - break - before: right. Constants: always/auto/get/left/right - its - column - break - inside: logical; Constant: avoid/ auto-webkit-column-count: 3; // -webkit-column-rule: 1px solid # FFF; style:dashed,dotted,double,groove,hidden,inset,none,outset,ridge,solid
⑩ UI description attributes refer to user interface elements in the browser, such as the scroll text area or scroll bar. The report also describes properties outside the scope of the web content, such as the annotation style of the cursor and the display when you hold down a touch to touch a target, such as a link on the iPhone.
- its - box - align: baseline, center, end, start, stretch constants: baseline/center/end/start/stretch - its - box - direction: normal; Constant: normal/ reverse-webkit-box-flex: flex_valuet-webkit-box-flex-group: group_number-webkit-box-lines: multiple; Multiple/single-webkit-box-ordinal-group: group_number-webkit-box-orient: block-axis; multiple/ single-webkit-box-ordinal-group: group_number-webkit-box-orient: block-axis; Constants: block - axis/horizontal/inline - axis/vertical orientation - its box - pack: alignment; Constants: center/end/the justify/start
Animation Transitions This is the most innovative feature in Webkit: the use of transition functions to define animations.
-webkit-animation: title infinite ease-in-out 3s; Animation has the following attributes: -webkit-animation-name: // The property name is keyframes -webkit-animation-duration: 3s // duration -webkit-animation-timing-function: // Transition type: Ease/linear /ease-in /ease-out /ease-in-out /cubic- bezier-webkit-animation -delay: 10ms // Animation delay (default 0) -webkit-animation-iteration-count: // Number of cycles (default 1), infinite -webkit-animation-direction: // Animation mode: Normal (default forward play); Alternate (alternate direction, even number of forward play, odd number of reverse play)
These can also be abbreviated. But what really gets me going is keyFrames, which defines the transition process for an animation to be called, from 0% to 100% or from(0%) to(100%). To put it simply, it’s as simple as having an idea of how you want the elements to change during the process.
-webkit-transform: type (scale/ rotate/ skew/ shift translate) Scale (num,num) Magnification. ScaleX and scaleY(3) can be abbreviated as scale(*, *) rotate(*deg). RotateX and rotateY can be rotate(*, *) Skew(*deg). SkewX and skewY can be abbreviated as skew(*,*) translate(*,*) coordinates move. TranslateX and translateY: translate(*, *)
Page description
This property is the icon used when the user saves the connection to the mobile desktop, otherwise a screenshot of the web page will be used. With this, you can let your web page live on your phone like an APP
This is the APP startup screen picture, which is similar to the above. If it is not set, the startup screen will be blank, and the pixel of the picture will be the pixel of the whole screen of the phone
Safari HTML Reference-supported Meta Tags is used to set the time and signal bar of the web app to black
Common screen parameters
- Device resolution Device pixel ratio
- Android LDPI 320 x 240 0.75
- Iphone 3 & Android MDPI 320×480 1
- Android HDPI 480 x 800 1.5
- The Iphone 4 960 x 640 2.0
A CSS pixel on the iPhone 4 actually looks like a 2×2 pixel. So the image looks like it’s been zoomed in twice, blurry.
Solutions:
1. Page references
2. CSS file
#header { background:url(mdpi/bg.png); } @media screen and (-webkit-device-pixel-ratio: 2) {/*CSS for high-density screens*/ #header {background:url(hdpi/bg.png); 3) {/*CSS for high-density screens*/ #header {background:url(hdpi/bg.png); }}
Mobile Web development tips
Click and click events
Click navigation for the A tag is handled by default in the onclick event. Mobile clients respond to onClick with a significant delay of several hundred milliseconds compared to PC browsers.
The sequence of responses to touch events in a mobile browser should be:
ontouchstart -> ontouchmove -> ontouchend -> onclick
Therefore, if you really want to speed up the response to click events, you should bind the onTouchEnd event.
Use click to give the element a style like the following
- its - tap - highlight - color: rgba (0,0,0,0);
If you don’t use click, you can’t simply use TouchStart or Touchend instead, you need to simulate a click event with TouchStart, and you can’t have a TouchMove event, or a Tap event in Zepto.
body { -webkit-overflow-scrolling: touch; }
Isn’t it nice to scroll through long web pages on an iPhone or iPad? But if it’s a div, then set height:200px; overflow:auto; You can scroll but you don’t have that sliding effect at all. Pretty depressing, huh?
I’ve seen a lot of websites using third-party libraries to achieve this effect. The most common one is Iscroll (sina mobile page, Baidu, etc.), which I used at first, but since -webkit-overflow-scrolling: touch; After styling, you can completely discard the third party library and add it to the body{} section, and all overflow scrolling will work.
Lock viewport
Ontouchmove ="event.preventDefault()" // Lock viewPort, any on-screen action will not move the UI (except for the pop-up keyboard).
Media Query believes most people have already used it. JavaScript can be used in conjunction with Media Query:
var mql = window.matchMedia("(orientation: portrait)"); mql.addListener(handleOrientationChange); handleOrientationChange(mql); function handleOrientationChange(mql) { if (mql.matches) { alert('The device is currently in portrait orientation ') } else { alert('The device is currently in landscape orientation') }}
With the help of the Media Query interface to do event listening, so very powerful!
You can also use Media Query to determine device conditions by obtaining CSS values. For details, see: how JavaScript determines devices based on CSS Media Queries.
Rem Best Practices
Rem is a very useful attribute that can be benchmarked based on HTML and is compatible. But sometimes you still need to gracefully downgrade some browsers that don’t make sense. Here are two practices
HTML {the font - size: 62.5%; } body { font-size: 14px; The font - size: 1.4 rem; } /* =14px */ h1 { font-size: 24px; The font - size: 2.4 rem; } /* =24px */
Current click element style:
- its - tap - highlight - color: color
Detect iPhone/iPod
The first thing you need to do to develop a device specific mobile site is device detection. Here’s how tO use Javascript to detect iPhone/iPod uAs and then switch to the specific URL.
If ((the navigator userAgent. Match (/ iPhone/I)) | | (the navigator. UserAgent. Match (/ iPod/I))) {if (document.cookie.indexOf("iphone_redirect=false") == -1) {window.location = "http://m.example.com"; }}
Javascript can run on fruit devices, but users can disable it. It also causes client-side refreshes and additional data transfers, so here is server-side detection and redirection:
If (STRSTR ($_SERVER [' HTTP_USER_AGENT '], 'iPhone') | | STRSTR ($_SERVER [' HTTP_USER_AGENT '], 'iPod')) {header (' Location: http://yoursite.com/iphone "); exit(); }
Prevents the font from automatically adjusting when the screen rotates
html, body, form, fieldset, p, div, h1, h2, h3, h4, h5, h6 {-webkit-text-size-adjust:none; }
Emulation: Hover pseudo-class
Because the iPhone does not have a mouse pointer, there is no hover event. The CSS: Hover pseudo-class is useless. But the iPhone has Touch events, so onTouchStart is like onMouseOver, and onTouchEnd is like onMouseOut. So we can use it to simulate hover. The use of Javascript:
var myLinks = document.getElementsByTagName('a'); for(var i = 0; i < myLinks.length; I ++){myLinks[I].adDeventListener (' touchStart ', function(){this.className = "hover"; }, false); MyLinks [I] addEventListener (' touchend ', function () {enclosing the className = ""; }, false); }
Then add the hover effect with CSS:
A :hover, a.hover {/* your hover effect */}
Design a link this way to feel more like a button. And this simulation can be applied to any element.
Flexbox layout
Flex templates and instances
Learn more about Flexbox expansion box models
CSS Flexbox Intro
www.w3.org/TR/css3-fle…
Center problem
Center is a nightmare for both mobile and PC. There are two new solutions that are compatible.
-
Table layout method
.box{ text-align:center; display:table-cell; vertical-align:middle; }
-
The old flex layout method
.box{ display:-webkit-box; -webkit-box-pack: center; -webkit-box-align: center; text-align:center; }
These are the cornerstones of retchat and Ionic, respectively.
Here are more detailed more options www.zhouwenbin.com/%E5%9E%82%E… From zhou Wenbin’s blog
Handle Retina double screen
Using CSS Sprites to optimize your website for Retina Displays
Optimize the image display for Apple’s Retina screen using CSS3’s background-size
Use CSS Sprites to optimize your website for Retina display
CSS IMAGE SPRITES FOR RETINA (HIRES) DEVICES
This is really the browser’s own processing. The browser adds the datepicker module for this type of input.
Placeholder input Type dates are in place to allow users to input date formats more accurately. There will be datepicker in iOS that doesn’t display placeholder text, but in order to keep the look and feel of the form consistent, you’ll need placeholder text. Some Android models don’t have datepicker and won’t display placeholder text.
Desktop (Mac)
- Datepicker not supported by Safari, placeholder normal display.
- Firefox does not support datepicker, placeholder normal display.
- Chrome supports Datepicker, which displays year, month, and day formats, ignoring placeholder.
The mobile terminal
- IPhone5 iOS7 has datepicker, but not placeholder.
- ■ Andorid 4.0.4 without datepicker, placeholder not displayed
Solutions:
Because text is placeholder supported. So when you focus, you automatically change type to Date, so you have placeholder and datepicker
Viewport causes text to fold without cause
www.iunbug.com/archives/20…
Guide the user to install and open the app
From gallery.kissyui.com/redirectToN… Kissy Mobile sends a request through iframe SRC to open app custom URL scheme, such as Taobao ://home and etao://scan). If the client is installed, it will be directly aroused. After being aroused directly, the previous browser window (or the webview of the scan tool) will be pushed into the background. If the client is not aroused within the specified time, js is redirected to the app download address. The approximate implementation code is as follows
goToNative:function(){ if(! body) { setTimeout(function(){ doc.body.appendChild(iframe); }, 0); } else { body.appendChild(iframe); } setTimeout(function() { doc.body.removeChild(iframe); gotoDownload(startTime); /** * When the test time is less than 800ms, the UC browser under Android will open the native APP and download the APK. * The test time of opening Native under Android +UC is better than 800ms; * /}, 800); }
It is important to note If android is the chrome version later, 25 in the iframe SRC will not send the request, here’s why developers.google.com/chrome/mobi… The intent mechanism can be used to pull up the client via location href and the current page does not jump.
window.location = 'intent://' + schemeUrl + '#Intent; scheme=' + scheme + '; package=' + self.package + '; end';
Js8. in/2013/12/16/…
Active Compatibility (from Duanyang Xue)
To make the CSS active pseudo-class work, you only need to bind an empty anonymous method to any of the touchStart/Touchend events of the touch series
a { color: #000; } a:active { color: #fff; } asdasd
Remove the Transition screen
Two methods: when using CSS3 animations, try to use 3D acceleration to make the animations smooth. Animation during the animation flash white can be hidden by using backface-visibility.
-webkit-transform-style: preserve-3d; /* Set how embedded elements will be rendered in 3D space: leave 3D*/ -webkit-backface-visibility: hidden; /* (sets whether the back of the converted element is visible from the user: hidden) */
Test whether SVG images are supported
Document. Implementation. HasFeature (" http:// www.w3.org/TR/SVG11/feature#Image ", "1.1")
“Privacy Mode”
Reference address: blog. Youyo. Name/archives/sm…
Safari on ios provides a “privacy mode”. If your webapp is considering compatibility with this mode, it may throw an error when using ————localStorage, a type of localStorage in html5, because it does not have permission to read or write localstorge in “privacy mode”. Resulting in subsequent JS code can not run.
In Safari privacy mode, you do not have permission to call localStorage. The first thing that comes to mind is whether to support localStorage.
If ('localStorage' in window){// Need to use localStorage code here}else{// unsupported hint and backward compatibility code}
The test found that even in Safari’s privacy mode, ‘localStorage’ in window returned true, meaning that the code inside the if block still ran, and the problem was not resolved. The next step is to use a try catch, although this is not recommended, to catch the error so that the following JS code can continue to run:
Try {if('localStorage' in window){else{// Unsupported hint and backcompatible code}}catch(e){// Privacy mode related prompt code and unsupported prompt and backward compatibility code}
So, be aware that in cases where ios compatible Safari’s “privacy mode” is required, local storage related code needs to be wrapped with try catch and degraded compatibility.
Android phone click lock page effect problem
On some Android phones, when a page is clicked, it stops the execution of javascript, CSS3 animations, etc., which can be a pain. However, this can be resolved by blocking the default event. Detailed see stackoverflow.com/questions/1…
function touchHandlerDummy(e) { e.preventDefault(); return false; } document.addEventListener("touchstart", touchHandlerDummy, false); document.addEventListener("touchmove", touchHandlerDummy, false); document.addEventListener("touchend", touchHandlerDummy, false);
Eliminate the cross in IE10
IE Pseudo-elements
input:-ms-clear{display:none; }
About ios and OS side font optimization
Chinese font optimization for Web pages on MAC
UIWebView font is thinner in portrait than landscape
Check whether the user “after adding the page to the home screen, then open the page from the home screen”
navigator.standalone
Hide the address bar & prevent the scroll bar from appearing when processing events:
AddEventListener ('load', function(){setTimeout(function(){window.scrollto (0, 1); }, 100); });
Check whether it is iPhone:
/ / determine whether for the iPhone: the function isAppleMobile () {return (the navigator. Platform. IndexOf (' the ')! = 1); };
localStorage:
var v = localStorage.getItem('n') ? localStorage.getItem('n') : ""; // If data with name n exists, it is read and assigned to variable v. localStorage.setItem('n', v); // Write data with name n and value v localstorage.removeitem ('n'); // Delete data named n
Use special links:
If you turn off auto-id and want certain phone numbers to be linked to your iPhone’s dialing function, you can declare phone links like this,
Call me texting
Or for cells:
Auto capitalization with auto correction
To turn both features off, you can use the autocapitalize and Autocorrect options:
Don’t let Android recognize email
Disable iOS operation Windows
-webkit-touch-callout:none
Disallows the user to select text
-webkit-user-select:none
Translate performs better than positioning in animation effects
Why Moving Elements With Translate() Is Better Than Pos:abs Top/left
Get the scroll bar
window.scrollY window.scrollX
For example, to bind a TouchMove event, normally something like this (from breathing carbon dioxide)
$(' div ') on (' touchmove ', function () {/ /.... .code {});
If the code in the middle has a lot of stuff to handle, the FPS is going to go down and affect the smoothness of the program, whereas if it goes like this
$(' div ') on (' touchmove ', function () {setTimeout (function () {/ /.... .code },0); {});
If you put your code in setTimeout, you’ll see that it gets faster.
About the adaptability Settings of Web APP startup pictures on different devices in iOS system
Stackoverflow.com/questions/4…
Position :sticky and position: Fixed layout
www.zhouwenbin.com/positionsti… www.zhouwenbin.com/sticky%E6%A…
In iOS, when you enter English in the Chinese input method, there may be a space of one sixth between letters
You can get rid of it by re
this.value = this.value.replace(/\u2006/g, '');
About the weird case of input element input in android WebView
See below
Android Web View, at least on the HTC EVO and Samsung Galaxy Nexus, has text fields that act like placeholders when typed. The situation is that there is something like a watermark in the user’s input area that disappears once the user starts typing (see image).
Under the default style of Android, when the input box gets the focus, if there is an absolutely positioned or fixed element, the layout will be destroyed, and other elements will overlap with the system input field (for example, the search icon will disappear as the search field). It can be observed that the layout is deviated from the original input field (see screenshot).
This is a fairly complex problem, and the following simple layout can reproduce it:
Phone: *
The solution
-webkit-user-modify: read-write-plaintext-only
A detailed reference www.bielousov.com/2012/androi… Note that this property will result in no phrase being entered in Chinese, only a single word. Thanks to Ghost brother and Fei (You Yongfei) for contributing to this problem and solution
Also, try not to use input fields in the position:fixed element. More bugs may refer to www.cosdiv.com/page/M0/S88…
If not, use input:text instead of password and set it to -webkit-text-security: disc; Hide the input password to solve.
The dynamically generated select dropdown menu does not work in the default browser on Android2.x
Overflow-x :hidden; Then focus on the menu after JS generation. The problem is solved after these two steps. (From Shimadu – Xiao Qi)
Reference stackoverflow.com/questions/4…
Remove the voice input button from Android
input::-webkit-input-speech-button {display: none}
Special mouse events for IE10
Internet Explorer 10 event listening
IOS input box best practices
Mobile-friendly input of a digits + spaces string (a credit card number)
HTML5 input type number vs tel
iPhone: numeric keyboard for text input
Text Programming Guide for iOS – Managing the Keyboard
HTML5 inputs and attribute support
Round-trip caching issues
Click back in the browser, sometimes js is not automatically executed, especially in Mobilessafari. This is related to the round-trip cache (BFCache). There are a lot of hack handling methods, you can refer to
Stackoverflow.com/questions/2…
Stackoverflow.com/questions/1…
The timer
www.imququ.com/post/ios-no… Another way to use work is to write ing.
Audio and Video
By default, audio’s autoplay attribute does not take effect, which is also considered by mobile phones to save user traffic. If you have to autoplay, there are two ways to do it.
1. Capture user input once, let the audio load, can play next time.
//play and pause it once document.addEventListener('touchstart', function () { document.getElementsByTagName('audio')[0].play(); document.getElementsByTagName('audio')[0].pause(); });
This method requires capturing a user click event to force audio and video to load. Once loaded, you can use javascript to control the playback of the audio, such as calling audio.play().
2. Use iframe to load resources
var ifr=document.createElement("iframe"); ifr.setAttribute('src', "http://mysite.com/myvideo.mp4"); ifr.setAttribute('width', '1px'); ifr.setAttribute('height', '1px'); ifr.setAttribute('scrolling', 'no'); ifr.style.border="0px"; document.body.appendChild(ifr);
This way is actually the same as the first principle. You can control the playback when the resource is loaded, but here iframe is used to load the resource directly. Note that it is not feasible to create the audio tag and have it load. Careful use of this method can have a terrible effect on users.
IOS 6 and iPhone 5
IP5 media query
@media (device-height: 568px) and (-webkit-min-device-pixel-ratio: 2) { /* iPhone 5 or iPod Touch 5th generation */ }
Media query, respond to different startup images
Photo upload
Other types of files, such as audio, Pages documents or PDF files, are not supported. There is also no live streaming support for getUserMedia cameras.
HTML5 advanced apis available
- Multipart POST form submission upload
- XMLHttpRequest 2 AJAX Upload (even progress support)
- The file API in iOS 6 allows JavaScript to directly read the number of bytes and the client to manipulate the file.
Smart application banner
With Smart Application Banners, Safari can display a banner when there is an associated native application on the site. If the user does not have the application installed, the install button will be displayed, or the installed view button will be displayed to open it.
Search for our app and app ID in iTunes Link Maker.
You can use app-argument to provide string values, and you can add meta tag data if you participate in the iTunes Alliance program
The banner needs to be 156 pixels (312 hi-dpi for devices) at the top, and your site won’t display its full height until the user clicks the content or close button below. It’s like an HTML DOM object, but it’s not really a DOM.
CSS 3 filters
-webkit-filter: blur(5px) grayscale (.5) opacity(0.66) hue-rotate(100deg);
Cross light change
background-image: -webkit-cross-fade(url("logo1.png"), url("logo2.png"), 50%);
Full screen in Safari
In addition to chrome-less home screen meta tabs, iphones and iPod Touch (but not on ipads) now support full-screen mode Windows. There is no way to force full-screen mode, it needs to be started by the user (the last icon on the toolbar). You need to instruct the user to press the full-screen icon on the screen to activate the full-screen effect. You can use the onresize event to detect if the user switches to the full screen.
Support requestAnimationFrameAPI
Support for image-set,retina display
-webkit-image-set(url(low.png) 1x, url(hi.jpg) 2x)
Application cache limit increased to 25MB.
Web View (Pseudogap /Cordova applications, embedded browsers) Javascript runs 3.3 times slower than Safari (or is the Nitro engine 3.3 times faster than Web applications in Safari).
The input to the Autocomplete attribute follows THE DOM specification
Mutation Observers from DOM4 have been implemented. You can capture DOM changes using the WebKitMutationObserver constructor
Safari no longer always creates hardware acceleration for elements using -webkit-Transform: preserve-3D
Selection API for window.selection is supported
Canvas update: createImageData has one parameter and is now ready with two new features to provide high-resolution images with webkitGetImageDataHD and webkitPutImageDataHD.
Update the SVG handler and event constructor
IOS7
Safari and HTML5 for iOS 7: Issues, Changes and new apis
IOS 7: Some Pitfalls
Some potholes in ios7
The webview associated
Enable and set Cache
browser.getSettings().setAppCacheEnabled(true); browser.getSettings().setAppCachePath("/data/data/[com.packagename]/cache"); browser.getSettings().setAppCacheMaxSize(5*1024*1024); // 5MB
LocalStorage Related Settings
browser.getSettings().setDatabaseEnabled(true); browser.getSettings().setDomStorageEnabled(true); String databasePath = browser.getContext().getDir("databases", Context.MODE_PRIVATE).getPath(); browser.getSettings().setDatabasePath(databasePath); // There is a problem with LocalStorage in Androidwebview. It will be clear after closing the APP or restarting it, so browser.getSettings().setdatabase is required. Putting into the DB myWebView LocalStoarge. SetWebChromeClient (new WebChromeClient () {@ Override public void onExceededDatabaseQuota(String url, String databaseIdentifier, long currentQuota, long estimatedSize, Long totalUsedQuota, webstorage.quotaupdater QuotaUpdater {QuotaUpdater. UpdateQuota (estimatedSize * 2); }}
The browser has its own zoom button to cancel the display
browser.getSettings().setBuiltInZoomControls(false);
A few good practices
Use localStorage to cache HTML
With LazyLoad, remember that the LazyLoad placeholder, although small, is best loaded into the cache ahead of time
Lazy loading executes JS
The main reason is the onPageFinished event of the Android Webview. Android usually uses this event to indicate that the page has been loaded and displayed. In other words, loading will continue until then. However, Android’s OnPageFinished event will not fire until the Javascript script has finished executing. $(document).ready(function() {}); The page is rendered and displayed after the event.
Mobile adaptation
Mobile phone packet capture and host configuration
On a PC, we can easily configure host, but on a mobile phone, how to configure host, this is a problem.
Fiddler and remote agent are mainly used here to realize the operation of mobile phone with host. Specific operations are as follows:
First, ensure that the PC and mobile device are on the same LAN.
Start Fiddler on PC and select “Allow remote Computers to Connect” in Settings.
-
First, ensure that the PC and mobile device are on the same LAN.
-
Start Fiddler on PC and select “Allow remote Computers to Connect” in Settings.
-
Set the proxy on your phone with the IP address of your PC and port 8888 (the default fiddler port). Usually, the proxy can be set directly on the phone. If not, you can download an APP called ProxyDroid to set the proxy.
-
You’ll find that when you use your phone to surf the Internet, you’re actually using Fiddler on your PC. All request packets will be listed in Fiddler, and when willow uses them, you can configure the host or even reverse proxy.
CCProxy software can also be used, there is another way is to buy a portable wifi, and then mobile phone connection can be!
Senior caught
Use Burp Suite to capture HTTPS communication packet methods on iPhone
Mobile APP Communication Analysis Method (iOS/Android)
Capture packets on mobile devices in real time (ADVsock2pipe+Wireshark+ NC +tcpdump)
Static resource caching problem
Nocache can be set for static resources proxy by proxy software to avoid caching. However, some mobile phones are weird and will always cache CSS and other resource files. Since static resources are generally managed by version numbers, we use Charles as an example to deal with this problem
Charles selects the static HTML page file -saveResponse. Then save the file and change the version number. To continue the request, right-click the HTML file and select map local and select the HTML file whose version number has been changed. This is actually a case where Fiddler maps and modifies files remotely.
Mobile Browser
Wechat browser
Because wechat browser blocks some linked pictures, users need to be guided to open a new page. The ua of wechat browser can be judged in the following ways
function is_weixn(){ var ua = navigator.userAgent.toLowerCase(); if(ua.match(/MicroMessenger/i)=="micromessenger") { return true; } else { return false; }}
Back-end judgment is also simple, such as PHP
function is_weixin(){ if ( strpos($_SERVER['HTTP_USER_AGENT'], 'MicroMessenger') ! == false ) { return true; } return false; }
UC Browser The video label is disconnected from the document flow
Scenario: After the parent element of the tag is set to the Transform style, the tag will leave the document flow.
Test environment: UC browser 8.7/8.6 + Android 2.3/4.0.
Demo: tc n/zj3xiyu
Solution: Do not use the transform property. Translate is replaced with attributes such as top and margin.
【UC Browser 】 The video TAB always comes first
Scenario: The label is always the first (the z-index attribute of the video label is Max).
Test environment: UC browser 8.7/8.6 + Android 2.3/4.0.
[UC Browser] Position: Abnormal phenomenon of fixed attribute in UC browser
Scenario: Elements with position: fixed will block peers with higher Z-index values.
In 8.6, this happens directly.
In versions after 8.7, it is blocked only when the height of a peer element is greater than the “magic” value of 713.
Test environment: UC Browser 8.8_beta/8.7/8.6 + Android 2.3/4.0.
Demo: tc n/zYLTSg6
QQ mobile browser does not support HttpOnly
Scenario: Cookies with HttpOnly attribute are invalid in QQ mobile browser version 4.0. JavaScript can directly read Cookie values set to HttpOnly.
Test environment: QQ mobile browser 4.0/4.1/4.2 + Android 4.0.
[MIUI native Browser] The browser address bar hash does not change
Scenario: After location.hash is assigned, the address in the address bar does not change.
But the location. Href is already updated, and you can easily get the updated address using JavaScript.
Although normal access is not affected, users cannot bookmark the hash address changed during access.
Test environment: MIUI 4.0
Fixed elements cannot be clicked
Scene: Parent element set position: fixed;
The child element sets position: absolute;
If the parent/child element also sets overflow: hidden, the parent element blocks the child element.
There is no occlusion in the view layer, but events bound to the child cannot be triggered. I can’t see the point.
Add: Scroll down the page, triggering position: fixed; This bug will not appear at the top.
Test platform: mi 1S, Chrome18 on Android4.0
Demo: maplejan.sinaapp.com/demo/fixed_…
Solution: Remove overflow: Hidden from parent and child elements.
The above comes from www.cnblogs.com/maplejan/ar…
Library usage practices
zepto.js
Zepto an article on the use of caution points
Zepto’s famous tap “tap through” bug
Zepto source notes
Using ZeptoJS embedded in android WebView affects normal scrolling
Github.com/madrobby/ze… By removing 61 lines, you’re essentially using native scrolling
Several bugs iscroll4 (from www.mansonchor.com/blog/blog_d… Detailed explanation)
1. No response from scroll container when clicking input box, SELECT, etc.
onBeforeScrollStart: function (e) { e.preventDefault(); }
onBeforeScrollStart: The function (e) {var nodeType = e.e xplicitOriginalTarget © e.e xplicitOriginalTarget. NodeName. ToLowerCase () : (e. arget © e.target.nodeName.toLowerCase():''); if(nodeType ! ='select'&& nodeType ! ='option'&& nodeType ! ='input'&& nodeType! ='textarea') e.preventDefault(); }
2. Container flash bug when adding content to iscroll container
The source code
has3d = 'WebKitCSSMatrix' in window && 'm11' in new WebKitCSSMatrix()
has3d = false
UseTransition is set to false when iscroll is configured
3. Scrolling content is too long, which leads to lag and app flash back directly
- Do not use checkDOMChanges. While checkDOMChanges is convenient to refresh periodically to check for changes in container length, it also means that you consume an Interval of memory space
- Hide the iscroll scroll bar and set hScrollbar and vScrollbar to false during configuration.
- If necessary, remove all effects and set momentum, useTransform, and useTransition to false
4. When scrolling left and right, the text cannot be pulled up and down properly
Iscroll flash problem is also related to rendering, can refer to the use of WebKit rendering page principle to solve iscroll4 flash problem iscroll4 upgrade to 5 to pay attention to the problem
The following solution can be used (utilizing the data-set API)
The mystery of the dead pig in the Huangpu River
You can also do it this way
$(document).delegate('[data-target]', 'touchmove', function () { $(this).attr('moving','moving'); }) $(document).delegate('[data-target]', 'touchend', function () { if ($(this).attr('moving') ! == 'moving') {// Do what you want. $(this).attr('moving', 'notMoving'); } else { $(this).attr('moving', 'notMoving'); }})
Mobile font problem
Zhihu Column – [Wireless Manual -4] DP, SP, PX
Resolution Independent Mobile UI
Pixel density, retina display and font-size in CSS
Device pixel density tests
Cross-domain problem
Mobile browsers are also browsers and have cross-domain issues with Ajax calls to external apis. Of course, with PhoneGap packaging, there is no cross-domain problem due to different protocols. But pages usually need to be debugged with the back end. They usually report something like that
XMLHttpRequest cannot load XXX Origin null is not allowed by Access-Control-Allow-Origin.
XMLHttpRequest cannot load http://. Request header field Content-Type is not allowed by Access-Control-Allow-Headers."
You can add two HTTP headers to the back end
Access-Control-Allow-Origin "*" Access-Control-Allow-Headers "Origin, X-Requested-With, Content-Type, Accept"
The first header avoids cross-domain issues, and the second header makes it easy for Ajax requests to set configuration items such as content-Type
This will be some safety problems, can refer to the discussion at www.zhihu.com/question/22…
PhoneGap part
Snoopyxdy.blog.163.com/blog/static… Here’s a bunch of Snoopy summaries of phongGap development pits
Should not happen: no rect-based-test nodes found
Add the following code to the HTML page within Assets in the Android project to solve the problem
window,html,body{ overflow-x:hidden ! important; -webkit-overflow-scrolling: touch ! important; overflow: scroll ! important; }
Reference:
Stackoverflow.com/questions/1…
The problem may be caused by the window.onload binding that the Navigator fetches from contacts
Note that when using PhoneGap’s API, be sure to use the API in the Devicereay event handler
document.addEventListener("deviceready", onDeviceReady, false); function onDeviceReady() { callFetchContacts(); } function callFetchContacts(){ var options = new ContactFindOptions(); options.multiple = true; var fields = ["displayName", "name","phoneNumbers"]; navigator.contacts.find(fields, onSuccess, onError,options); }
IOS Safari BUG Summary
Safari has a weird BUG with the DOM element bubbling mechanism that only works on iOS
For BUG recurrence cases, see online DEMO: address
Bug presentation and avoidance
Delegating an event directly to the body of an element that does not exist in the DOM will cause the event delegate to fail. The debugging result is that the event response reaches the body child element, neither bubbling on nor being caught by the body. However, if the event is owned by the DOM element itself, the bug will not be triggered. In other words, only nonstandard events of an element (such as a click event for a div) trigger the bug.
Because the bug is caused by Safari’s event resolution mechanism, it cannot be fixed, but there are several ways to circumvent it
-
How to avoid bug triggering: Instead of delegating to the body node, delegate to any specified parent element, or use an element that has the event natively, such as the A tag for the click event.
-
If an event has been responded to before, it will bubble (catch) all the way to the root, so for mass triggered cases, just bind an empty event to all children of the body element, as in:
("body > *").on("click", function(){};) ;
May have some impact on performance, but easy to use, we weigh it ~~~