转载:轻量级浏览器特性检测库:feature.js
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
演示:
- Official site with live tests: http://featurejs.com
- Test with actual features: http://featurejs.com/test
注明出处格式:前端开发博客 (http://caibaojian.com/feature-js.html)
转载:轻量级浏览器特性检测库:feature.js的更多相关文章
- 浏览器特性检测插件Feature.js
<script src="js/feature.js"></script> if (feature.webGL) { console.log("你 ...
- 2016 年 50 个最佳的轻量级 JavaScript 框架和库
作者:IT程序狮链接:https://zhuanlan.zhihu.com/p/24598210来源:知乎著作权归作者所有.商业转载请联系作者获得授权,非商业转载请注明出处. 回顾今年已发布的 JS ...
- js+jquery检测用户浏览器型号(包括对360浏览器的检测)
做网站,js检测用户浏览器的版本,是经常要使用到,今天自己写了一个js,完成了对于一些常见浏览器的检测,但是,偏偏对于360浏览器的检测没有任 何办法,研究了一会儿,无果.无论是360安全浏览器,还是 ...
- 翻译连载 | 附录 C:函数式编程函数库-《JavaScript轻量级函数式编程》 |《你不知道的JS》姊妹篇
原文地址:Functional-Light-JS 原文作者:Kyle Simpson-<You-Dont-Know-JS>作者 关于译者:这是一个流淌着沪江血液的纯粹工程:认真,是 HTM ...
- 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. ...
- websocket-heartbeat-js心跳检测库正式发布
前言: 两年前写了一篇websocket心跳的博客——初探和实现websocket心跳重连. 阅读量一直比较大,加上最近考虑写一个自己的npm包,因此就完成了一个websocket心跳的检测库.在这 ...
- Atitit. Atiposter 发帖机 新特性 poster new feature v7 q39
Atitit. Atiposter 发帖机 新特性 poster new feature v7 q39 V8 重构iocutilV4,use def iocFact...jettyUtil V ...
- Atitit. Atiposter 发帖机 新特性 poster new feature v7 q39
Atitit. Atiposter 发帖机 新特性 poster new feature v7 q39 V1 初步实现sina csdn cnblogs V2 实现qzone sohu 的发帖 ...
- 深入探讨 CSS 特性检测 @supports 与 Modernizr
什么是 CSS 特性检测?我们知道,前端技术日新月异的今天,各种新技术新属性层出不穷.在 CSS 层面亦不例外. 一些新属性能极大提升用户体验以及减少工程师的工作量,并且在当下的前端氛围下: 很多实验 ...
随机推荐
- Bootstrap关于表单控件(按扭)
按钮也是表单重要控件之一,制作按钮通常使用下面代码来实现: ☑ input[type=“submit”] ☑ input[type=“button”] ☑ input[type=“r ...
- MySQL 存储过程的异常处理
mysql> mysql> delimiter $$ mysql> mysql> CREATE PROCEDURE myProc -> (p_first_ ...
- 于工具类中@Autowired注入为NULL的问题记录
记录:在实体类中加入@Component注解和@Autowired注解时Service不能注入成功. ? 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 ...
- 1009MySQL数据库InnoDB存储引擎Log漫游
00 – Undo Log Undo Log 是为了实现事务的原子性,在MySQL数据库InnoDB存储引擎中,还用Undo Log来实现多版本并发控制(简称:MVCC). - 事务的原子性(Atom ...
- HDU 4530
今天让人看不起了,话说好伤心,说我搞了ACM那么久都没获得拿得出手的奖.... 今晚爷爷我要狂刷2013腾讯马拉松的水题,奶奶滴,哈哈哈哈...T_T #include <iostream> ...
- POJ 2007
直接求凸包,输出即可. #include <iostream> #include <cstdio> #include <cstring> #include < ...
- HDUOJ--4888--Redraw Beautiful Drawings【isap】网络流+判环
链接:http://acm.hdu.edu.cn/showproblem.php? pid=4888 题意:一个矩阵.限定每行行和.列和,每一个格子数字不超过k,问矩阵是否存在,如存在推断有单解还是多 ...
- 区间最小值 线段树 (2015年 JXNU_ACS 算法组暑假第一次周赛)
区间最小值 Time Limit : 3000/1000ms (Java/Other) Memory Limit : 65535/32768K (Java/Other) Total Submiss ...
- Leetcode 贪心 Best Time to Buy and Sell Stock
本文为senlie原创.转载请保留此地址:http://blog.csdn.net/zhengsenlie Best Time to Buy and Sell Stock Total Accepted ...
- Codeforces Round #200 (Div. 2)D. Alternating Current (堆栈)
D. Alternating Current time limit per test 1 second memory limit per test 256 megabytes input standa ...