_javascript techniques for sniffing and feature detection of JavaScript frame design browsers

Source: Internet
Author: User

Browser sniffing is now deprecated, but it is needed on some occasions. For example, some statistical scripts. In the standard browser, provided the document.implementation.hasfeature, unfortunately there are bugs, inaccurate, at present, the Css.supports has launched a new method, showing the attention of this piece.

1. Decision Browser.

Mainstream browsers have IE Firefox opera chorme Safari early these frameworks are judged by the navigator.useragent, the current foreign browsers are almost all can be judged.

On the browser's judgment script, jquery has moved out of the ontology to form a plugin. More ways not to introduce more,

The relevant decision of mobile device, this suggestion looks at jquery Mobile and Zepto source code.

Copy Code code as follows:

Isipone =/isipone/i.test (navigator.useragent);
IsIPone4 = Window.devicepixelratio >= 2///In Web pages, pixel and point ratios are called device-pixel-ratio, common devices are 1,iphone4 2, and some Android models are 1.5
Isipad =/ipad/i.test (navigator.useragent)
Isandroid =/android/i.test (navigator.useragent)
Isios = Isipone | | Isipad

Domestic browser decision can see Tangrame or qwrap, they are basically ie,webkit,blink kernel.

2. Event Support Detection

Prototype's core member, Kangax, wrote an article to determine the browser's support for some kind of event. Here are the following implementations:

  var iseventsupported = (function () {
    var tagnames = {
      ' select ': ' Input ', ' change ': ' Input ',
      ' submit ': ' Form ', ' Reset ': ' form ', '
      error ': ' img ', ' Load ': ' img ', ' Abort ': ' img '
    }
    function iseventsupported (eventName) {
      var el = document.createelement (Tagnames[eventname] | | ' Div ');
      EventName = ' on ' + eventName;
      var issupported = (eventName in EL);
      if (!issupported) {
        el.setattribute (eventName, ' return; ');
        issupported = typeof El[eventname] = = ' function ';
      }
      el = null;
      return issupported;
    }
    return iseventsupported;
  }) ();

Now the framework for jquery is a simplified version of using scripting

But which is good, this test only works for DOM0, like Dommousescroll domcontentloaded domfocusin domfocusout domsubtreemodified domnoderemoved domnoderemovedfromdocument domnodeinsertedintodocument domattrmodified Domcharactordatamodified these things that begin with Dom are powerless.

Some of these events are very useful, such as Dommousescroll,firefox has not supported Mousesheel, can only use it as a substitute.
Domcontentloaded is an important event to implement Domready, domnoderemoved is to determine whether the element is removed from its parent node, and the parent node may be another element node or document fragment; domnoderemovedfromdocument is to move away from the DOM tree, domattrmodified used to simulate IE onpropertychange

CSS3 adds two kinds of animations, one is transition animation, the other is keyframe motion tween. They use event callbacks at the end of the event. But in the process of standardization, browsers give them names that are equivalent to no rules. This also needs to be detected in advance.

Here is the implementation of the bootstrap. Heard from Modernizr, relatively rough. For example, the oprera you are using has been supported with no event standard event names. It still returns to the Otransitionend.

  $.supports.transition = (function () {
    var transitionend = (function () {
      var el = document.createelement (' Bootstarp '),
          transendeventnames = {
            ' webkittransition ': ' Webkittransitionend ',
            ' moztransition ': ' Transitionend ',
            ' otransition ': ' Otransitionend otransitionend ',
            ' transition ': ' Transitionend '
          };
        for (var name in transendeventnames) {
          if (El.style[name]!== undefined) {return
            transendeventnames[name]
          }
        }
    } ());
    Return transitionend && {
      end:transitionend
    }
  }) ();

Keyframe motion tween from mass Fx_neo module

  var eventName = {
    animationevent: ' Animationend ',
    webkiranimationevent: ' Webkiranimationend '
  }, Animationend;
  for (var name in eventName) {
    if (/object|function/.test (typeof Window[name))) {
      animationend = eventname[name]< C7/>break
    }
  }

3. Style of support detective

CSS3 brings a lot of handy styles, but the trouble is that each browser has its own private prefix, Massframework provides a cssname method to handle them, and returns the available hump style name, without null

  var prefixes = [', '-webkit-', '-o-', '-moz-', '-ms-'];
  var cssmap = {
    "float": $.support.cssfloat? ' Cssfloat ': ' stylefloat ', background: ' BackgroundColor '
  };
  function Cssname (name, host, CamelCase) {
    if (cssmap[name)) {return
      cssmap[name];
    }
    Host = Host | | Document.documentelement for
    (var i = 0 | | = n = prefixes.length; i < n; i++) {
      CamelCase = $. String.camelize (Prefixes[i] + name);
      if (CamelCase in host) {return
        (cssmap[name] = CamelCase)
      }} return
    null
  }

A style for n style values, such as display has n values, if you want to detect whether the browser supports a certain, it can be cumbersome. To do this, the browser did a charity, give a Css.supports API, if not supported, then try the next open source project. Obviously, it's not perfect.

Https://github.com/termi/CSS.supports

The meaning of some common features of 4.jQuery

jquery has some common DOM feature support cases in the support module, but the names are very strange and different versions vary greatly, and this chapter takes jQuery1.8 as the subject.

Leadingwhitespace: Determine the browser in the innerHTML assignment, whether there are trimleft operations, this function was originally IE invented, the results of other browsers that the original value to be loyal to the next, the front of the blank can not be God, to become a text node, Final IE678 returns false, other browsers return True

Tobody: Refers to the dynamic creation of elements with innerHTML, whether the browser will automatically fill in the table tobody,jquery want the browser do not handle, let jquery to complete. Determines whether the browser can only insert Tobody. In the age of tabular layouts, this feature is very useful. If no tbody,table is displayed when the browser resolves to a closed tag. If the starting and closing tags are far apart, in other words, the table is very long, the user will not see anything, but with the tbody segmentation display and recognition, to avoid a long time blank after a sudden display of the situation.

Copy Code code as follows:

var div = document.createelement ("div");
div.innerhtml = ' <table></table> '
Alert (div.innerhtml)//=>ie678 return to <table><tbody></tbody></table>, other return <table>< /table>

Html. Serialize: To determine whether the browser is intact to support the use of innerHTML to convert a string that conforms to the HTML tag rule as an element node, this process jquery is called serialization, but IE support is not intact. No-scope elements, including the SCIRPT link style Mata, have failed to convert.

Style: This name is difficult to understand, do not look at the code does not know what the meaning, really like is to determine whether GetAttribute return style user preset. IE678 does not return a feature that distinguishes attributes, and returns a Cssstyledeclaration object.

Hrefnormalized: Determines whether GetAttribute can return the user preset for href. IE will add you the full path to your

Opacity: Determine if the browser supports opacity properties, ie678 to use filters

Cssfloat: The style of the judgement float is that in the name of the DOM, the cssfloat,ie678 for stylefloat

Checkon: The value of the checkbox in most browsers is On,chorme returns an empty string

Optselected: Deciding whether to get the dynamic add option element correctly seleted,ie6-10 and the old version of Safari are not set to true for dynamic add option. Workaround, access the SelectedIndex property of the parent node before accessing the selected property, and then force the calculation of option seleted.

<select id= ' optselected ' ></select>
<script type= ' text/javascript ' >
  var select = document.getElementById (' optselected ');
  var option = document.createelement (' option ');
  Select.appendchild (option);
  alert (option.selected);
  Select.selectedindex;
  Alert (option.selected)
</script>

Optdisabled: Determines whether the Disable property of the Select element affects the disabled value of the child element. In Safari, once a SELECT element is disabled, its child elements are also disabled, resulting in a value that is not

Checkclone: Refers to a checkbox element, if the checked=true is set, and its replicas remain true after multiple clones. This method only returns false in Safari4, and the other is true

Inlineblockneedslayout: Determine if the Haslayout method is used to make the dispaly:inline-block effective. This method only ie678 is True

Getsetattribute: Determines whether attribute attributes are distinguished, only ie678 is False

Nocloneevent: Determines whether to clone attachevent binding events when cloning elements. Only older versions of IE and their compatibility mode return FALSE

Enctype: Determines whether the browser supports encoding properties, IE67 uses the encoding property instead

Boxmodel: Determines whether the browser is in Content-box box rendering mode

Submitbubbles, Changebubbles, focusinbubble: Determine if the browser supports these events and has been bubbling to document

Shrinkwrapblocks: Determines whether the element will be stretched by the quilt element. In IE678, a replacement element supports its parent element when the size and haslayout are set.

Html5clone: Determine whether to use CloneNode clone HTML5 new label, older version of IE does not support. Need to use outerHTML

Deleteexpando: Determines whether custom elements on element nodes can be deleted, which is used for the jquery caching system. Older versions of IE are not supported, direct undefined

Pixelposition: Determines whether getComputedStyle can convert the percentage value of the top left bottom right element of an element. This is going to be a problem in the WebKit system that needs to be used by Dean Edwards God hack

Reliablemarginright: Determine whether getComputedStyle can get the marginriht of elements correctly.

CLEARCLONESTYLE:IE9 10 will be a strange bug, when you copy an element of the background-*-style elements, the copied elements are emptied, the original style is emptied.

With the browser crazy update version, standard browser caused by a variety of bugs have gone beyond IE, feature detection is not back, more and more important.

The above mentioned is the entire content of this article, I hope you can enjoy.

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.