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. datawhale爬虫实训4

    DataWhale-Task4(爬取丁香园2) 任务:使用lxml爬虫帖子相关的回复与部分用户信息(用户名,头像地址,回复详情) 难点:需要登录才能看到所有回复 浏览器登录上去,查看cookies信息 ...

  2. 12.IDEA中自动导资源包

    在idea工程中,当你赋值一个类文件的部分代码,粘贴到另一个文件中时,需要导入原来文件中的包资源, 自动设置如下

  3. 关于Java中返回零长度数组或空集合比较好,还是返回null这个问题的一些想法

    近日在方法返回类型为List数据类型时,返回结果为空集合比较好,还是null比较好的问题上有点纠结. 我觉得应该统一返回空集合,这样可以不用进行空指针的判断,不然又多了一个产生bug的可能性.而有人认 ...

  4. sendfile学习

    参考 https://zhuanlan.zhihu.com/p/20768200?refer=auxten 而成本很多时候的体现就是对计算资源的消耗,其中最重要的一个资源就是CPU资源. Sendfi ...

  5. Android传统HTTP请求get----post方式提交数据(包括乱码问题)

    1.模仿登入页面显示(使用传统方式是面向过程的) 使用Apache公司提供的HttpClient  API是面向对象的 (文章底部含有源码的连接,包括了使用async框架) (解决中文乱码的问题.主要 ...

  6. 从编程的角度理解gradle脚本﹘﹘Android Studio脚本构建和编程[魅族Degao]

    本篇文章由嵌入式企鹅圈原创团队.魅族资深project师degao撰写. 随着Android 开发环境从Eclipse转向Android Studio,我们每一个人都開始或多或少要接触gradle脚本 ...

  7. WinForm使用CefSharp内嵌chrome浏览器

    先贴运行图:亲测可用!以图为证! 开始!1.创建winform程序,使用.NET 4.5.2或以上(vs2010最高支持.NET 4.0,我使用的是vs2017).这一步容易忽略,简单的说就是将项目. ...

  8. 实战c++中的vector系列--vector应用之STL的find、find_if、find_end、find_first_of、find_if_not(C++11)

    使用vector容器,即避免不了进行查找,所以今天就罗列一些stl的find算法应用于vector中. find() Returns an iterator to the first element ...

  9. Vultr好server不敢独享

    Vultr是一家美国2014年成立的新公司.瞬间红遍世界,他是干什么的?他是serverVPS(Virtual Private Server)提供商,这个价格真实惊人的廉价5美金/月.折合人民币30元 ...

  10. Java封装FushionCharts

    近期公司接了个关于数据统计的系统.须要用到报表功能.找了几天认为还是FushionCharts 适合.所以就对FushionCharts进行了java代码封装,方便,前台,后台调用. 1.报表Mode ...