HTML5: Understand Polyfills, HTML5: Polyfills

Source: Internet
Author: User

HTML5: Understand Polyfills, HTML5: Polyfills

Using HTML5 to build websites and applications may be a daunting task. Although more and more modern browsers are now supporting new Html5 features, only a few are lucky to write code for these latest browsers. As a professional developer, you must spend a lot of energy adjusting the unfreedom of space layout, implementing the promised features, and facing the current reality. These are all due to browser fragmentation. The good news is that both Internet Explorer 9 and Internet Explorer 10 support HTML5. You can discard the old version of Internet Explorer, but developers still need to consider supporting the old version of Web browsers.

In any case, this does not mean that you must give up using HTML5 in the next time. Fortunately, the website can use many technologies to elegantly support a variety of different situations, such as a variety of screen sizes and different CSS functions, these technologies can also achieve amazing comprehensive cross-browser HTML5 support. Although the old browser lacks many new HTML5 APIs, JavaScript is an incredible restoration language that can append features not supported by many browsers.

 

Cross-browser support

The most difficult problem with using HTML5 in a large number is that we should not choose to support old browsers, but they have little or no support for new APIs. Adapting to the new Web technology makes us shudder to cross-browser differences, as well as branch code, browser detection, and a bunch of other problems that are difficult to maintain. However, we also have a low-key technology that can alleviate these problems. Although your users may have upgraded their browsers to the latest one after a night, this function is polyfills.

 

Polyfilling is a term proposed by RemySharp. It is used to describe the behavior of copying missing APIs and API functions. You can use it to write code for individual applications without worrying about native support from other browsers. In fact, polyfills is neither a new technology nor a combination of HTML5. We have already used it in JS that provides transparent PNG support for IE browsers like json2.js. The difference from polyfills is the HTML5 polyfills added last year.

 

What is Polyfill?

For details, let's take a look at json2.js. Pay special attention to the JSON. parse of the first line:

1If(TypeofJSON. parse! = 'Function '){

2 // Crockford's JavaScript implementation of JSON. parse

3}

Use typeof to test this code. If the Browser executes JSON. parse in a native way, json2.js will not interfere with or redefine it. If the native API is unavailable, json2.js will execute a JavaScript script to implement it. It is fully compatible with the native json api. Finally, you can use json2.js on the webpage without considering which code the browser runs.

 

This shows the advantages of polyfilling-not only in compatibility, but also in the implementation method close to standard APIs. In addition, you do not need to know the special code of those sites or consider the existence of the compatibility layer. Finally, we will see a clean, simple, and site-specific code. Other old browsers can also use the new API.

 

HTML5 new semantic elements

In HTML5, the simplest feature of polyfil is to set the added semantic elements, such as <article>, <aside>,

Fortunately, Sjoerd Visscher found a simple solution for IE, and John Resig carried it forward. Call document. createElement () when using any element form, so that IE can use all the styles in CSS.

 

For example, you can call document. createElement ('Article') in

1<Html>

2<Head>

3<Title>HTML5 Now? </Title>

4<Style>

5 article {margin: 0 auto; width: 960px ;}

6 </style>

7<Script>

8 document. createElement ('Article ');

9 </script>

10

11<Body>

12<Article>

13 <! -- TODO: Write article... -->

14 </article>

15 </body>

16

Example 1: Call document. createElement to change the CSS style of the IE browser application

 

However, no one wants to manually add the createElement Declaration for so many newly added semantic elements in html5. This is what polyfill is best. One of them is html5shim (that is, html5shiv), which automatically sets the compatibility between IE browser and new semantic elements.

For example, the Code in Example 1 can be reconstructed using html5shim. See example 2.

 

1<Html>

2<Head>

3<Title>HTML5 Now! </Title>

4<Style>

5 article {margin: 0 auto; width: 960px ;}

6 </style>

7<! -- [If ltIE 9]>

8 <script src = "http://html5shim.googlecode.com/svn/trunk/html5.js"> </script>

9<! [Endif] -->

10

11<Body>

12<Article>

13 <! -- TODO: Write article... -->

14 </article>

15 </body>

16

Example 2 Use html5shim polyfill

Note that the descriptions around the script refer to html5shim. This ensures that this polyfill will only be loaded on IE browsers older than IE9. Other browsers that support the new semantic elements do not have to waste time downloading, pausing, or executing them.

Another option to consider

If you are very interested in HTML5 and read this article, you may already know how to use Modernizr. However, you may not know that Modernizr has built the html5shim function. If you use Modernizr to test features, you are no longer compatible with the new HTML5 features.

 

Persistent client Storage

For many years, apart from solving the vendor's proprietary DOM extension and self-built plug-ins to maintain the browser's long-term status, we have no choice. These solutions include Firefox's globalStorage, IE's userData, cookies, and Google Gears. Although these solutions are feasible, these solutions are outdated, tedious, difficult to maintain, and error-prone.

 

One of the most popular extensions in HTML is localStorage, a standard API for the long-term storage of browser data. This API provides a continuous client/server-side key/value storage, which can store up to 5 MB of independent data for each website accessed by each user. You can use localStorage as an easy-to-use huge cookie without requiring the browser and server to make HTTP requests each time. LocalStorage is the perfect partner for browser-specific data projects, just like remembering preferences and local cached remote data.

 

Now all advanced browsers support the localStorage feature, and IE8 is also included. However, it is not supported in earlier versions than IE8. At the same time, there is still a polyfill cross-browser storage that allows the old version of browsers to support this feature. From simple Storage polyfiller of RemySharp to backward compatible store. js and PersistJS, as well as LawnChair's full-featured API and AmplifyJS Storage module.

 

For example, you may use the AmplifyJS storage module to store data in the user's browser without using cookies-even if the user uses IE6:

1 // Sets a localStorage variable 'name' with my Name in it.

2 amplify. store ('name', 'Dave Ward ');

3VarWebsite ={

4 name: 'encodesia ',

5 url: 'http: // encosia.com'

6}

7 // The library takes care of serializingobjects automatically.

8 amplify. store ('website', website );

Pulling that dataout at a later date becomes extremely easy:

1 // The values we stored before cocould thenbe used at a later time, even

2 // during a different session.

3Var$ PersonLink = $ ('<a> ',{

4 text: amplify. store ('name '),

5 href: amplify. store ('website'). url

6});

7 $ personLink. appendTo ('body ');

The advantage of using localStorage or the localStorage-based API is that data does not need to go through every HTTP request or call heavyweight plug-ins like Flash to store data. Data is stored in a real, independent local storage mechanism, which makes it easy to cache data locally and develop websites that require good support for offline use.

 

What to use

Remy Sharp's Storage Polyfiller is the only one that can be used as polyfill, because none of the others can perfectly imitate the HTML5 localStorage API. However, the store. js and AmplifyJS storage modules provide a wide range of compatibility with old browsers, which is hard to ignore.

 

Geographic location

Geographic location is another mature polyfill HTML5 feature. If browsers and Operating Systems Support geographic locations and their devices are equipped with GPS sensors, HTML5 provides the geographic location API feature that allows JavaScript code to determine where your page is accessed.

 

Mobile devices are the most surprising example of browser-based geographic location usage. The built-in GPS hardware module is integrated with modern browsers to support the HTML5 geographic location API. Android and iOS devices support HTML5 geographic location, and are as accurate as native applications.

 

In those environments with good conditions, JavaScript needs to access the geographical location, which is as simple as the following:

1 navigator. geolocation. getCurrentPosition (Function(Position){

2VarLat = position. coords. latitude;

3VarLong = position. coords. longpolling;

4 console. log ('current location: ', lat, log );

5});

This is great for mobile apps, but desktop devices are usually not equipped with GPS sensors and we are all used to it. However, location-based advertisements that are common around us are longer than geographic location APIs. Therefore, you can obtain geographical locations in a desktop browsing environment that lacks hardware support.

 

The current method of JavaScript is to find the visitor's IP address in the known IP location library. This is obviously not accurate with GPS devices, but these databases are usually able to accurately locate the region, which is sufficient for many applications.

 

You may already know that GPS-less location positioning is not only dependent on finding IP addresses. Generally, these methods for enhancing positioning accuracy are completed with the help of the Wi-Fi hotspot location library. Unfortunately, the JavaScript code running in the browser cannot call information from the underlying system. Therefore, polyfill currently does not support Wi-Fi-based technology. We can use IP address lookup instead.

Paul Irish writes a simple geographic location polyfill that can be located for the old browser and hardware that lacks GPS sensors. It uses Google's geographic location API to convert users' IP addresses into similar physical geographic locations. It is a real polyfill that adds the geographic location function to the navigator. geolocation object, but it is used only when the browser does not provide the geographic location API.

 

Browsing History and navigation

The simple DHTML effect provides more structured client features, such as AJAX-based paging and single-page interfaces. These structure changes are not synchronized with the built-in navigation and history functions of the browser. When users naturally try to use their return button to return to the previous page or application status, this is not the case. When we search for the "Disable return button", we will find the impact of this problem on modern web development.

 

The "Hash" section of the browser address can help us solve some problems. Because Hash is originally used to jump between different navigation points on the same page, changing the Hash value of the link does not refresh the page as if it were changed to the relevant link prefix. The Hash value allows the client to synchronize with the JavaScript driver to maintain the address displayed by the browser, so that you do not need to use traditional navigation events.

 

Onhashchange event

When the Hash part of the browser is well supported, or even connected to IE6, it is not until the latest standard method for monitoring Hash changes has become elusive. Recently, the new browser supports the onhashchange event. When the Hash part of the address changes, it is triggered-it can perfectly detect the situation that users want to change the client status through browser navigation control. Unfortunately, the onhashchange event is only supported by relatively new browsers, since IE8 and Firefox 3.6.

Although the onhashchange event does not support the old browser, it can provide an abstract library file for the old browser. These compatible layers use the unique attributes of the browser to copy standard onhashchangge events. They can even monitor location. hash multiple times every second and respond when the address Hash value changes in the browser.

A good choice is Ben Alman's jQuery Hashchange plug-in, which he extracted from his own popular jQueryBBQ plug-in. Alman's jQueryHashchange provides a very deep cross-browser hashchange event compatibility. I'm a bit hesitant to call it polyfill, because it requires jQuery and cannot accurately copy the native API, but it is really great when jQuery is already used on your page!

Beyond HashState

Operating the Hash value is a good way to solve the client status management problem, but it still has shortcomings. Since the link based on Hash value will confuse users and conflict with the existing navigation on the page, it is not the best way to control the browser navigation feature.

A more fundamental problem is that the browser does not add the Hash part of the browser request to the HTTP request. There is no Hash location in the access link, so it is impossible to immediately return to the same status after the user bookmarks the page, receives it via email, or shares it through social networks. As a result, the website can only display their default pages, and the initial status will jump to the desired position through a awkward conversion. To prove the usability impact, you just need to take a look at Twitter and Gawker Media's "hash bang" re-design.

 

Enter pushState

Fortunately, HTML5 introduces a more advanced API that significantly improves the client's history management solution. It is usually called pushState, which is similar to windows. history. pushState method and window. the onopstate event is combined to provide a method to asynchronously process the address path of the entire browser and respond to navigation events outside the Hash.

Viewing the project code on Github is the best example of using pushState in reality. Because the processing of browser addresses through pushState does not refresh the entire page as the traditional address changes, Github can provide transition animations between each code page switch, and the links are user-friendly, instead of Hash tags or query strings.

Even better, if you save one of the links as bookmarks and then access the link, Github will immediately give you the correct content when you first request it, because the link structure on the client is the same as that on the server. As I mentioned earlier, using Hash-based links is impossible, because the server has nothing to do with Hash requests.

 

Use onhashchange and pushState in your code

Unfortunately, it is impossible to add the pushState feature not supported by the browser to the real polyfill pushState. Without the abstract layer, you can change the fact that changing the link in the old browser will redirect the browser to and load the page. However, you can use it in a browser that supports pushState, instead of using a Hash-based link in an unsupported old browser.

 

Benjamin Luton built a great cross-browser library that effectively addresses the wide range of strange and inconsistent phenomena encountered when managing client history. This library can be used in Chrome from IE6 to the latest version. The usage is also very simple. It has a syntax that is very similar to the pushState Syntax of HTML5:

1 // This changes the URL to/state1 in HTML5 browsers, and changes it

2 /// #/state1 in older browsers.

3 History. pushState (null, 'state 1', 'state1 ');

4 // Same as before, but/state2 and/#/state2.

5 History. pushState (null, 'state 2', 'state2 ');

Compared to accurately copying HTML5 popstate events, history. js contains many types of adapters that can be run in coordination with the event systems in those libraries. For example, with the jQuery adapter, You can bind an event handler to the statechange event of history. js, just like this:

1 History. Adapter. bind (window, 'statchange ',Function(){

2 // Get the newhistory state from history. js.

3VarState = History. getState ();

4 // Write the URLwe 've navigated to on the console.

5 console. log (state. url );

6});

Through the pushState method of history. js, The statechange event handler is triggered every time the browser navigating to the historical node maintained by the pushState method of history. js. Whether the native HTML5 browser that supports pushState or the old browser that only supports link Hash changes, this event is monitored to capture each activity.

 

It is very easy to apply this to practical applications. You can imagine using it in paging and sorting of tables provided by AJAX, or even whole-site navigation (such as Gmail and Twitter ), they do not need to rely on Hash links and redirection that everyone hates.

Run with pushScissors

One thing to note when using pushState is that you must ensure that the server can properly adapt to each link on the client. Because it is easy for you to establish a client link to your server with a 404 or 500 Error Response (for example,/undefined ), this ensures that your server can handle unexpected links as elegantly as possible during sending or URL rewriting. For example, if you have a multi-page report under/report and use pushState to split it into/report/1,/report/2,/report/3, and so on, you must ensure that the server code can respond elegantly to/report/undefined links.

Another alternative is to use the link segment of the query string in your pushState address, like/report? Page number = 2 and/report? Page number = 3. In this way, the final links may not look good, but at least they will not cause 404 errors.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.