Example of whether JavaScript detection supports CSS3, HTML5 new features

Source: Internet
Author: User
Tags datetime touch


With the release of the HTML5 Standard Edition at the end of October this year, the future use of H5 will be more and more, which is what makes Web developers rejoice. However, there is a reality we have to see, that is, IE series browser also occupies a large part of the market share, to IE8, 9-oriented, windows8.1 users have used the IE10/11, and consider our national conditions, IE6, 7 still remain a lot. The new feature support test is essential when we let go of the HTML5 development. One way is to use navigator.useragent or navigator.appname to detect browser type and version, but this is not very reliable, browsers for some new features are also gradually support, it is not certain that a browser 100% support the HTML5. Moreover, IE11 made a disgusting move: Remove the "MSIE" flag in UA, change appname to "Netspace", and begin to support the CSS attribute of the-webkit-prefix, which is a vivid disguise for the rhythm of chrome. Therefore, HTML5/CSS3 support detection, or by feature detection (figure detection) or the ability to detect better. This article will introduce the common detection methods are what.

Add: Judge IE11 still available this way:/trident/i.test (navigator.appversion), get from moustache.

HTML5 part

There are several ways to detect new features of HTML5:

1. Check that there are no corresponding property names on the Global Object (window or navigator)

2. Create an element to check that there are no corresponding attributes on the element

3. Create an element to detect if there is a method name on the element, and then call the method to see if it executes correctly

4. Create an element, assign a value to the corresponding property of the element, and then get the value of this property to see if the assignment takes effect

Because of the different behavior of different browsers, the detection of some features, may use the combination of the above several methods, and then use the above methods to do the common characteristics of the detection:

Canvas

function Support_canvas () {
var elem = document.createelement (' canvas ');
Return!! (Elem.getcontext && elem.getcontext (' 2d '));
}
Generally, create canvas elements and check the GetContext properties, but in some browsers is not accurate enough, so check the Elem.getcontext (' 2d ') of the execution results, you can completely determine. The above code is excerpted from modernizr:http://github.com/modernizr/modernizr/issues/issue/97/

One thing to add to the canvas is that the Filltext method, although browsers support canvas, is not exactly sure that it supports the Filltext method, because the canvas API undergoes various modifications, and there are historical reasons The methods for detecting support for Filltext are as follows:

function Support_canvas_text () {
var elem = document.createelement (' canvas ');
var context = Elem.getcontext (' 2d ');
return typeof Context.filltext = = ' function ';
}
Video/audio

function Support_video () {
Return!! Document.createelement (' video '). Canplaytype;
}

function Support_audio () {
Return!! Document.createelement (' audio '). Canplaytype;
}
Video and audio are similar.

To detect Video/audio supported resource formats, you can call the Canplaytype method for checking, as follows:

Unction Support_video_ogg () {
var elem = document.createelement (' video ');
Return Elem.canplaytype (' Video/ogg; codecs= "Theora");
}
function support_video_h264 () {
var elem = document.createelement (' video ');
Return Elem.canplaytype (' Video/mp4; codecs= "avc1.42e01e");
}
function Support_video_webm () {
var elem = document.createelement (' video ');
Return Elem.canplaytype (' video/webm; codecs= "VP8, Vorbis");
}

function Support_audio_ogg () {
var elem = document.createelement (' audio ');
Return Elem.canplaytype (' Audio/ogg; codecs= "Vorbis");
}
function Support_audio_mp3 () {
var elem = document.createelement (' audio ');
Return Elem.canplaytype (' audio/mpeg; ');
}
function Support_audio_wav () {
var elem = document.createelement (' wav ');
Return Elem.canplaytype (' audio/wav; codecs= "1");
}
Note that the return value of the Canplaytype is not a Boolean type, but a string that has the following values:

"Probably": Browser fully supports this format
"Maybe": Browser may support this format
' ": empty string, indicating no support
Localstorage

Generally, check if the Global object has localstorage properties, as follows:

function Support_localstorage () {
try {
Return ' localstorage ' in Window && window[' localstorage ']!== null;
}
catch (e) {
return false;
}
}
In some browsers disable cookies, or set the privacy mode what the case, check the properties or error, so add in the try statement, if the error is not supported.

In addition, there is a more rigorous method of checking to see if the appropriate method supports the following:

function Support_localstorage () {
try {
if (' Localstorage ' in Window && window[' localstorage ']!== null) {
Localstorage.setitem (' test_str ', ' test_str ');
Localstorage.removeitem (' test_str ');
return true;
}
return false;
}
catch (e) {
return false;
}
}
Webworker

function Support_webworker () {
Return!! Window. Worker;
}
Applicationcache

function Support_applicationcache () {
Return!! Window.applicationcache;
}
Geolocation

function Support_geolocation () {
Return to ' geolocation ' in navigator;
}
Input label new attribute

Input tags new properties include: AutoComplete, autofocus, list, placeholder, max, Min, multiple, pattern, required, step, Check to see if the above Method 2 can be used to create a new input label to look for these properties, take AutoComplete as an example:

function Support_input_autocomplete () {
var elem = document.createelement (' input ');
Return to ' AutoComplete ' in Elem;
}
Also pay special attention to the List property, because it is used with the DataList tag, so check the time to detect the DataList tag support:

function Support_input_list () {
var elem = document.createelement (' input ');
Return!! (' list ' in Elem && document.createelement (' DataList ') && window. Htmldatalistelement);
}
Input label new type

The type is defined here, and the input new type value includes: Search, tel, url, email, datetime, date, month, week, time, datetime-local, number, range , color. Detecting these values requires the method 4 mentioned above, taking number as an example:

function Support_input_type_number () {
var elem = document.createelement (' input ');
Elem.setattribute (' type ', ' number ');
return elem.type!== ' text ';
}
This is a simpler way to check because, strictly speaking, browsers provide different skins or implementations for different types, such as the president of the range type in Chrome:

Use JavaScript to detect whether CSS3, HTML5 new features are supported

We want to know exactly what the browser provides for this type of implementation, can be considered to be "supported", to detect from this aspect is difficult, each browser implementation is different. Here is an implementation of the Modernizr, for reference: detection of email type implementation:

function Support_input_type_email () {
var elem = document.createelement (' input ');
Elem.setattribute (' type ', ' email ');
Elem.value = ':) ';
return elem.checkvalidity && elem.checkvalidity () = = false;
}
Set an illegal value for the email type, and then manually invoke the checksum method, which, if returned false, indicates that the browser provided the type of implementation that is supported.

History

History Although HTML4 has, but HTML5 provides a new method, detection methods are as follows:

function Support_history () {
Return!! (Window.history && history.pushstate);
}
Webgl

function Support_webgl () {
Return!! Window. Webglrenderingcontext;
}
PostMessage

function Support_postmessage () {
Return!! Window.postmessage;
}
Draggable

HTML5 drag and drop characteristics:

function support_draggable () {
var div = document.createelement (' div ');
Return (' draggable ' in div) | | (' ondragstart ' in div && ' ondrop ' in div);
}
WebSocket

Unction Support_websocket () {
Return to ' WebSocket ' in Window | | ' Mozwebsocket ' in window;
}
Svg

function Support_svg () {
Return!! Document.createelementns &&!! Document.createelementns (' http://www.w3.org/2000/svg ', ' svg '). Createsvgrect;
}
The support judgment of the event

Common methods:

Check the support of the event, using the method mentioned above 2, you can create an element to see if there is a corresponding event name on the element, the following is an excerpt from the MODERNIZR implementation:

iseventsupported = (function () {

var tagnames = {
' SELECT ': ' Input ', ' change ': ' Input ',
' Submit ': ' Form ', ' Reset ': ' Form ',
' ERROR ': ' img ', ' Load ': ' img ', ' Abort ': ' img '
};

function iseventsupported (eventName, Element) {

Element = Element | | Document.createelement (Tagnames[eventname] | | ' Div ');
EventName = ' on ' + eventName;

When using ' setattribute ', IE skips "unload", WebKit skips "unload" and "resize", whereas ' in ' "catches" those
var issupported = EventName in element;

        if (!issupported) {
          /If It has no ' setattribute ' (i.e. doesn ' t implement Node Interface), try generic element
  & nbsp;       if (!element.setattribute) {
             element = document.createelement (' div ');
         }
          if (Element.setattribute && Element.removeattribute) {
            Element.setattribute (EventName, "");
            issupported = is (Element[eventname], ' function ');

If property is created, "Remove it" (by setting value to ' undefined ')
if (!is (element[eventname], ' undefined ')) {
Element[eventname] = undefined;
}
Element.removeattribute (EventName);
}
}

element = null;
return issupported;
}
return iseventsupported;
})()
Touch events

If it's just a matter of checking if the touch event supports it, there's no need to write as many things as you can, simply write as follows:

function Support_touch_event () {
Return!! ((' Ontouchstart ' in window) | | window. Documenttouch && document instanceof Documenttouch);
}
Mozilla also provides a media query to detect the touch's support: touch-enabled, you can insert an element with this media query on the page to determine whether the touch event is supported. Reference: http://www.quirksmode.org/css/mediaqueries/touch.html

However, we do mobile development generally only consider WebKit kernel, Mozilla Way is not written, if necessary please refer to Modernizr source.

CSS3 part

Common methods

CSS3 Property support detection, mainly through the above methods mentioned in the 2 and 4来 check, but we want to check the element's style attribute. The other thing to mention is the browser private prefix, at this stage we use the CSS3 attribute most of which is to write the prefix, because the browser has not fully supported. We use the prefix is:-webkit-、-ms-、-o-、-moz-, as for the prefix-khtml-, this is the early use of safari, and now basically no one to use it, so the test time to save it. Modernizr removed the previous suffix of the detection, as described in:

The common code is as follows:

var support_css3 = (function () {
   var div = document.createelement (' div '),
   & nbsp;  vendors = ' Ms O Moz Webkit '. Split ('),
      len = vendors.length;
 
   return function (prop) {
      if (prop into Div.style) return true;
 
      prop = prop.replace (/^[a-z]/, function (val) {
     & nbsp;   return Val.touppercase ();
     });
 
      while (len--) {
         if (Vendors[len] + prop in Div.style) {
            return t Rue
        }
     }
      return false;
  };
}) ();

3D deformation

CSS3 3D deformation detection is slightly more complex, first of all to support the Perspective property, the second to support the Transform-style value of preserve-3d. Cannot detect with method 4, need to use the way of media query, the code is as follows:

Function support_css3_3d () {
    var docelement = document.documentelement;
     var support = SUPPORT_CSS3 (' perspective ');
    var body = document.body;
    if (Support && ' webkitperspective ' in Docelement.style) {
    & nbsp;   var style = document.createelement (' style ');
        style.type = ' text/css ';
        style.innerhtml = ' @media (transform-3d), (-webkit-transform-3d) {# css3_3d_test{left:9px;position:absolute;height:3px;} ';
        Body.appendchild (style);
        var div = document.createelement (' div ');
        div.id = ' css3_3d_test ';
        Body.appendchild (div);

Support = Div.offsetleft = = 9 && Div.offsetheight = = 3;

}
return support;
}
You need to use the SUPPORT_CSS3 method defined above to detect perspective.

Basic commonly used testing on these, some of the code is online search, and a part of the source from the Modernizr from the extraction. If the narration is wrong, please correct me.

In actual development, it is recommended to use MODERNIZR directly for testing, it has been encapsulated very beautiful. But if you're only testing a few properties, or you don't want to waste performance by loading an extra library, you can use the code to do a single test.

Write so much first, later have thought of to add.

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.