feature.js是一个很简单、快速和轻量级的浏览器特性检测库,它没有任何依赖,体积压缩最后只有1KB,它可以自动初始化,在你需要知道某个特性是否可用时,直接引入即可。以下中文为个人理解。

/*!
* FEATURE.JS 1.0.0, A Fast, simple and lightweight browser feature
* detection library in just 1kb.
*
* http://featurejs.com
*
* CSS 3D Transform, CSS Transform, CSS Transition, Canvas, SVG,
* addEventListener, querySelectorAll, matchMedia, classList API,
* placeholder, localStorage, History API, Viewport Units, REM Units,
* CORS, WebGL, Service Worker, Context Menu, Geolocation,
* Device Motion, Device Orientation, Touch, Async, Defer,
* Srcset, Sizes & Picture Element.
*
*
* USAGE EXAMPLE:
* if (feature.webGL) {
* console.log("webGL supported!");
* }
*
* Author: @viljamis, https://viljamis.com
*/ /* globals DocumentTouch */
;(function (window, document, undefined) {
"use strict"; // For minification only
var docEl = document.documentElement; /**
* Utilities
*/
var util = { /**
* Simple create element method
*/
create : function(el) {
return document.createElement(el);
}, /**
* Test if it's an old device that we want to filter out
*/
old : !!(/(Android\s(1.|2.))|(Silk\/1.)/i.test(navigator.userAgent)), /**
* Function that takes a standard CSS property name as a parameter and
* returns it's prefixed version valid for current browser it runs in
* 返回当前的css属性是否当前运行的浏览器,例如一个css属性transition,这个函数会遍历
* dummy.style['transition']/dummy.style["WebkitTransition"]/dummy.style["MozTransition"]/dummy.style["OTransition"]/dummy.style["msTransition"]
* 的值是否为true,是则返回该值
*/
pfx : (function() {
var style = document.createElement("dummy").style;
var prefixes = ["Webkit", "Moz", "O", "ms"];
var memory = {};
return function(prop) {
if (typeof memory[prop] === "undefined") {
var ucProp = prop.charAt(0).toUpperCase() + prop.substr(1),
props = (prop + " " + prefixes.join(ucProp + " ") + ucProp).split(" ");
memory[prop] = null;
for (var i in props) {
if (style[props[i]] !== undefined) {
memory[prop] = props[i];
break;
}
}
}
return memory[prop];
};
})() }; /**
* The Feature.js object
*
* @constructor
*/
function Feature() {} Feature.prototype = {
constructor : Feature, // Test if CSS 3D transforms are supported
css3Dtransform : (function() {
var test = (!util.old && util.pfx("perspective") !== null);
return !!test;
})(), // Test if CSS transforms are supported
cssTransform : (function() {
var test = (!util.old && util.pfx("transformOrigin") !== null);
return !!test;
})(), // Test if CSS transitions are supported
// 检测css transition属性是否支持
cssTransition : (function() {
var test = util.pfx("transition") !== null;
return !!test;
})(), // Test if addEventListener is supported
// 检测 addEventListener是否支持
addEventListener : !!window.addEventListener, // Test if querySelectorAll is supported
// 检测querySelectorAll是否支持
querySelectorAll : !!document.querySelectorAll, // Test if matchMedia is supported
// 检测媒体查询(media)是否支持
matchMedia : !!window.matchMedia, // Test if Device Motion is supported
// 检测device Motion是否支持
deviceMotion : ("DeviceMotionEvent" in window), // Test if Device Orientation is supported
deviceOrientation : ("DeviceOrientationEvent" in window), // Test if Context Menu is supported
contextMenu : ("contextMenu" in docEl && "HTMLMenuItemElement" in window), // Test if classList API is supported
// 检测classList是否支持
classList : ("classList" in docEl), // Test if placeholder attribute is supported
// 检测placeholder是否支持
placeholder : ("placeholder" in util.create("input")), // Test if localStorage is supported
localStorage : (function() {
var test = "x";
try {
localStorage.setItem(test, test);
localStorage.removeItem(test);
return true;
} catch(err) {
return false;
}
})(), // Test if History API is supported
historyAPI : (window.history && "pushState" in window.history), // Test if ServiceWorkers are supported
serviceWorker : ("serviceWorker" in navigator), // Test if viewport units are supported
viewportUnit : (function(el) {
try {
el.style.width = "1vw";
var test = el.style.width !== "";
return !!test;
} catch(err) {
return false;
}
})(util.create("dummy")), // Test if REM units are supported
remUnit : (function(el) {
try {
el.style.width = "1rem";
var test = el.style.width !== "";
return !!test;
} catch(err) {
return false;
}
})(util.create("dummy")), // Test if Canvas is supported
canvas : (function(el) {
return !!(el.getContext && el.getContext("2d"));
})(util.create("canvas")), // Test if SVG is supported
svg : !!document.createElementNS && !!document.createElementNS("http://www.w3.org/2000/svg", "svg").createSVGRect, // Test if WebGL is supported
webGL : (function(el) {
try {
return !!(window.WebGLRenderingContext && (el.getContext("webgl") || el.getContext("experimental-webgl")));
} catch(err) {
return false;
}
})(util.create("canvas")), // Test if cors is supported
cors : ("XMLHttpRequest" in window && "withCredentials" in new XMLHttpRequest()), // Tests if touch events are supported, but doesn't necessarily reflect a touchscreen device
touch : !!(("ontouchstart" in window) || window.navigator && window.navigator.msPointerEnabled && window.MSGesture || window.DocumentTouch && document instanceof DocumentTouch), // Test if async attribute is supported
async : ("async" in util.create("script")), // Test if defer attribute is supported
defer : ("defer" in util.create("script")), // Test if Geolocation is supported
geolocation : ("geolocation" in navigator), // Test if img srcset attribute is supported
srcset : ("srcset" in util.create("img")), // Test if img sizes attribute is supported
sizes : ("sizes" in util.create("img")), // Test if Picture element is supported
pictureElement : ("HTMLPictureElement" in window), // Run all the tests and add supported classes
//查找在该对象中所有不是testAll、不是对象引用并且结果为true的方法,存进classes,最后输出来
testAll : function() {
var classes = " js";
for (var test in this) {
if (test !== "testAll" && test !== "constructor" && this[test]) {
classes += " " + test;
}
}
docEl.className += classes.toLowerCase();
} }; /**
* Expose a public-facing API
*/
function expose() {
var ftr = new Feature();
return ftr;
}
window.feature = expose(); }(window, document));

总体只有1KB,可以快速检测当前浏览器是否支持css3的特性。

使用方法:

if (feature.webGL) {
console.log("WebGL supported");
} else {
console.log("WebGL not supported");
}

属性列表:

Below you’ll find a list of all the available browser feature tests and how to call them.

feature.async
feature.addEventListener
feature.canvas
feature.classList
feature.cors
feature.contextMenu
feature.css3Dtransform
feature.cssTransform
feature.cssTransition
feature.defer
feature.deviceMotion
feature.deviceOrientation
feature.geolocation
feature.historyAPI
feature.placeholder
feature.localStorage
feature.matchMedia
feature.pictureElement
feature.querySelectorAll
feature.remUnit
feature.serviceWorker
feature.sizes
feature.srcset
feature.svg
feature.touch
feature.viewportUnit
feature.webGL

演示:

原文链接:轻量级浏览器特性检测库:feature.js 版权所有,转载时请注明出处,违者必究。
注明出处格式:前端开发博客 (http://caibaojian.com/feature-js.html)

转载:轻量级浏览器特性检测库:feature.js的更多相关文章

  1. 浏览器特性检测插件Feature.js

    <script src="js/feature.js"></script> if (feature.webGL) { console.log("你 ...

  2. 2016 年 50 个最佳的轻量级 JavaScript 框架和库

    作者:IT程序狮链接:https://zhuanlan.zhihu.com/p/24598210来源:知乎著作权归作者所有.商业转载请联系作者获得授权,非商业转载请注明出处. 回顾今年已发布的 JS ...

  3. js+jquery检测用户浏览器型号(包括对360浏览器的检测)

    做网站,js检测用户浏览器的版本,是经常要使用到,今天自己写了一个js,完成了对于一些常见浏览器的检测,但是,偏偏对于360浏览器的检测没有任 何办法,研究了一会儿,无果.无论是360安全浏览器,还是 ...

  4. 翻译连载 | 附录 C:函数式编程函数库-《JavaScript轻量级函数式编程》 |《你不知道的JS》姊妹篇

    原文地址:Functional-Light-JS 原文作者:Kyle Simpson-<You-Dont-Know-JS>作者 关于译者:这是一个流淌着沪江血液的纯粹工程:认真,是 HTM ...

  5. Atitit. Atiposter 发帖机 新特性 poster new feature v11  .docx

    Atitit. Atiposter 发帖机 新特性 poster new feature v11  .docx 1.1.  版本历史1 2. 1. 未来版本规划2 2.1. V12版本规划2 2.2. ...

  6. websocket-heartbeat-js心跳检测库正式发布

    前言: 两年前写了一篇websocket心跳的博客——初探和实现websocket心跳重连.  阅读量一直比较大,加上最近考虑写一个自己的npm包,因此就完成了一个websocket心跳的检测库.在这 ...

  7. Atitit. Atiposter 发帖机 新特性 poster new feature   v7 q39

    Atitit. Atiposter 发帖机 新特性 poster new feature   v7 q39 V8   重构iocutilV4,use def iocFact...jettyUtil V ...

  8. Atitit. Atiposter 发帖机 新特性 poster new feature   v7 q39

    Atitit. Atiposter 发帖机 新特性 poster new feature   v7 q39 V1  初步实现sina csdn cnblogs V2  实现qzone sohu 的发帖 ...

  9. 深入探讨 CSS 特性检测 @supports 与 Modernizr

    什么是 CSS 特性检测?我们知道,前端技术日新月异的今天,各种新技术新属性层出不穷.在 CSS 层面亦不例外. 一些新属性能极大提升用户体验以及减少工程师的工作量,并且在当下的前端氛围下: 很多实验 ...

随机推荐

  1. tp5 封装百度地图api接口

    //服务器端api extend\Map <?php /** * 百度地图业务封装 */ class Map{ /** * 根据地址来获取经纬度 * @param $address */ pub ...

  2. 转载 - KMP算法祥解

    出处:http://www.cppblog.com/oosky/archive/2006/07/06/9486.html KMP字符串模式匹配详解 来自CSDN     A_B_C_ABC 网友 KM ...

  3. 洛谷 P2121 拆地毯

    P2121 拆地毯 题目背景 还记得 NOIP 2011 提高组 Day1 中的铺地毯吗?时光飞逝,光阴荏苒,三年过去了.组织者精心准备的颁奖典礼早已结束,留下的则是被人们踩过的地毯.请你来解决类似于 ...

  4. 基于java注解实现自己的orm框架

    ORM即Object Relation Mapping,Object就是对象,Relation就是关系数据库,Mapping映射,就是说Java中的对象和关系数据库中的表存在一种对应关系. 现在常见的 ...

  5. 用css3和canvas实现的蜂窝动画效果

    近期工作时研究了一下css3动画和js动画.主要是工作中为了增强页面的趣味性,大家都有意无意的加入了非常多动画效果.当然大部分都是css3动画效果.能够gpu加速,这会降低移动端的性能需求. 今天主要 ...

  6. Android中验证输入是否为汉字及手机号,邮箱验证,IP地址可用port号验证

    1,验证是否为汉字 // 验证昵称 private boolean verifyNickname() { String nickname = edt_username.getText().toStri ...

  7. 怎样 获取 ios的系统版本

    获得Ios系统版本的函数,比方 函数定义: [cpp] view plaincopy + (float)getIOSVersion; 函数实现: [cpp] view plaincopy + (flo ...

  8. cocos2d-x的gitignore配置

    # Ignore thumbnails created by windows Thumbs.db # Ignore files build by Visual Studio *.obj *.exe * ...

  9. 【Android归纳】Fragment生命周期-基于实验的最新总结

    如今非常多应用的开发都是基于FragmentActivity中嵌套Fragment进行开发的,所以,假设我们可以清晰地知道他们的生命周期,那么会使我们的开发变的easy. 对于Activity的生命周 ...

  10. dns tunnel 使用 nishang 下载TXT里的cmd(TXT里)实现CC command+ ceye实现数据外发

    摘自:https://hk.saowen.com/a/a06909f1c57cb8452db969b3deede4151de42a7d69f4bb52c5bf027033fb91bd Powershe ...