modernizr.js 42 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116
  1. /*!
  2. * Modernizr v2.0.6
  3. * http://www.modernizr.com
  4. *
  5. * Copyright (c) 2009-2011 Faruk Ates, Paul Irish, Alex Sexton
  6. * Dual-licensed under the BSD or MIT licenses: www.modernizr.com/license/
  7. */
  8. /*
  9. * Modernizr tests which native CSS3 and HTML5 features are available in
  10. * the current UA and makes the results available to you in two ways:
  11. * as properties on a global Modernizr object, and as classes on the
  12. * <html> element. This information allows you to progressively enhance
  13. * your pages with a granular level of control over the experience.
  14. *
  15. * Modernizr has an optional (not included) conditional resource loader
  16. * called Modernizr.load(), based on Yepnope.js (yepnopejs.com).
  17. * To get a build that includes Modernizr.load(), as well as choosing
  18. * which tests to include, go to www.modernizr.com/download/
  19. *
  20. * Authors Faruk Ates, Paul Irish, Alex Sexton,
  21. * Contributors Ryan Seddon, Ben Alman
  22. */
  23. window.Modernizr = (function( window, document, undefined ) {
  24. var version = '2.0.6',
  25. Modernizr = {},
  26. // option for enabling the HTML classes to be added
  27. enableClasses = true,
  28. docElement = document.documentElement,
  29. docHead = document.head || document.getElementsByTagName('head')[0],
  30. /**
  31. * Create our "modernizr" element that we do most feature tests on.
  32. */
  33. mod = 'modernizr',
  34. modElem = document.createElement(mod),
  35. mStyle = modElem.style,
  36. /**
  37. * Create the input element for various Web Forms feature tests.
  38. */
  39. inputElem = document.createElement('input'),
  40. smile = ':)',
  41. toString = Object.prototype.toString,
  42. // List of property values to set for css tests. See ticket #21
  43. prefixes = ' -webkit- -moz- -o- -ms- -khtml- '.split(' '),
  44. // Following spec is to expose vendor-specific style properties as:
  45. // elem.style.WebkitBorderRadius
  46. // and the following would be incorrect:
  47. // elem.style.webkitBorderRadius
  48. // Webkit ghosts their properties in lowercase but Opera & Moz do not.
  49. // Microsoft foregoes prefixes entirely <= IE8, but appears to
  50. // use a lowercase `ms` instead of the correct `Ms` in IE9
  51. // More here: http://github.com/Modernizr/Modernizr/issues/issue/21
  52. domPrefixes = 'Webkit Moz O ms Khtml'.split(' '),
  53. ns = {'svg': 'http://www.w3.org/2000/svg'},
  54. tests = {},
  55. inputs = {},
  56. attrs = {},
  57. classes = [],
  58. featureName, // used in testing loop
  59. // Inject element with style element and some CSS rules
  60. injectElementWithStyles = function( rule, callback, nodes, testnames ) {
  61. var style, ret, node,
  62. div = document.createElement('div');
  63. if ( parseInt(nodes, 10) ) {
  64. // In order not to give false positives we create a node for each test
  65. // This also allows the method to scale for unspecified uses
  66. while ( nodes-- ) {
  67. node = document.createElement('div');
  68. node.id = testnames ? testnames[nodes] : mod + (nodes + 1);
  69. div.appendChild(node);
  70. }
  71. }
  72. // <style> elements in IE6-9 are considered 'NoScope' elements and therefore will be removed
  73. // when injected with innerHTML. To get around this you need to prepend the 'NoScope' element
  74. // with a 'scoped' element, in our case the soft-hyphen entity as it won't mess with our measurements.
  75. // http://msdn.microsoft.com/en-us/library/ms533897%28VS.85%29.aspx
  76. style = ['&shy;', '<style>', rule, '</style>'].join('');
  77. div.id = mod;
  78. div.innerHTML += style;
  79. docElement.appendChild(div);
  80. ret = callback(div, rule);
  81. div.parentNode.removeChild(div);
  82. return !!ret;
  83. },
  84. // adapted from matchMedia polyfill
  85. // by Scott Jehl and Paul Irish
  86. // gist.github.com/786768
  87. testMediaQuery = function( mq ) {
  88. if ( window.matchMedia ) {
  89. return matchMedia(mq).matches;
  90. }
  91. var bool;
  92. injectElementWithStyles('@media ' + mq + ' { #' + mod + ' { position: absolute; } }', function( node ) {
  93. bool = (window.getComputedStyle ?
  94. getComputedStyle(node, null) :
  95. node.currentStyle)['position'] == 'absolute';
  96. });
  97. return bool;
  98. },
  99. /**
  100. * isEventSupported determines if a given element supports the given event
  101. * function from http://yura.thinkweb2.com/isEventSupported/
  102. */
  103. isEventSupported = (function() {
  104. var TAGNAMES = {
  105. 'select': 'input', 'change': 'input',
  106. 'submit': 'form', 'reset': 'form',
  107. 'error': 'img', 'load': 'img', 'abort': 'img'
  108. };
  109. function isEventSupported( eventName, element ) {
  110. element = element || document.createElement(TAGNAMES[eventName] || 'div');
  111. eventName = 'on' + eventName;
  112. // When using `setAttribute`, IE skips "unload", WebKit skips "unload" and "resize", whereas `in` "catches" those
  113. var isSupported = eventName in element;
  114. if ( !isSupported ) {
  115. // If it has no `setAttribute` (i.e. doesn't implement Node interface), try generic element
  116. if ( !element.setAttribute ) {
  117. element = document.createElement('div');
  118. }
  119. if ( element.setAttribute && element.removeAttribute ) {
  120. element.setAttribute(eventName, '');
  121. isSupported = is(element[eventName], 'function');
  122. // If property was created, "remove it" (by setting value to `undefined`)
  123. if ( !is(element[eventName], undefined) ) {
  124. element[eventName] = undefined;
  125. }
  126. element.removeAttribute(eventName);
  127. }
  128. }
  129. element = null;
  130. return isSupported;
  131. }
  132. return isEventSupported;
  133. })();
  134. // hasOwnProperty shim by kangax needed for Safari 2.0 support
  135. var _hasOwnProperty = ({}).hasOwnProperty, hasOwnProperty;
  136. if ( !is(_hasOwnProperty, undefined) && !is(_hasOwnProperty.call, undefined) ) {
  137. hasOwnProperty = function (object, property) {
  138. return _hasOwnProperty.call(object, property);
  139. };
  140. }
  141. else {
  142. hasOwnProperty = function (object, property) { /* yes, this can give false positives/negatives, but most of the time we don't care about those */
  143. return ((property in object) && is(object.constructor.prototype[property], undefined));
  144. };
  145. }
  146. /**
  147. * setCss applies given styles to the Modernizr DOM node.
  148. */
  149. function setCss( str ) {
  150. mStyle.cssText = str;
  151. }
  152. /**
  153. * setCssAll extrapolates all vendor-specific css strings.
  154. */
  155. function setCssAll( str1, str2 ) {
  156. return setCss(prefixes.join(str1 + ';') + ( str2 || '' ));
  157. }
  158. /**
  159. * is returns a boolean for if typeof obj is exactly type.
  160. */
  161. function is( obj, type ) {
  162. return typeof obj === type;
  163. }
  164. /**
  165. * contains returns a boolean for if substr is found within str.
  166. */
  167. function contains( str, substr ) {
  168. return !!~('' + str).indexOf(substr);
  169. }
  170. /**
  171. * testProps is a generic CSS / DOM property test; if a browser supports
  172. * a certain property, it won't return undefined for it.
  173. * A supported CSS property returns empty string when its not yet set.
  174. */
  175. function testProps( props, prefixed ) {
  176. for ( var i in props ) {
  177. if ( mStyle[ props[i] ] !== undefined ) {
  178. return prefixed == 'pfx' ? props[i] : true;
  179. }
  180. }
  181. return false;
  182. }
  183. /**
  184. * testPropsAll tests a list of DOM properties we want to check against.
  185. * We specify literally ALL possible (known and/or likely) properties on
  186. * the element including the non-vendor prefixed one, for forward-
  187. * compatibility.
  188. */
  189. function testPropsAll( prop, prefixed ) {
  190. var ucProp = prop.charAt(0).toUpperCase() + prop.substr(1),
  191. props = (prop + ' ' + domPrefixes.join(ucProp + ' ') + ucProp).split(' ');
  192. return testProps(props, prefixed);
  193. }
  194. /**
  195. * testBundle tests a list of CSS features that require element and style injection.
  196. * By bundling them together we can reduce the need to touch the DOM multiple times.
  197. */
  198. /*>>testBundle*/
  199. var testBundle = (function( styles, tests ) {
  200. var style = styles.join(''),
  201. len = tests.length;
  202. injectElementWithStyles(style, function( node, rule ) {
  203. var style = document.styleSheets[document.styleSheets.length - 1],
  204. // IE8 will bork if you create a custom build that excludes both fontface and generatedcontent tests.
  205. // So we check for cssRules and that there is a rule available
  206. // More here: https://github.com/Modernizr/Modernizr/issues/288 & https://github.com/Modernizr/Modernizr/issues/293
  207. cssText = style.cssRules && style.cssRules[0] ? style.cssRules[0].cssText : style.cssText || "",
  208. children = node.childNodes, hash = {};
  209. while ( len-- ) {
  210. hash[children[len].id] = children[len];
  211. }
  212. /*>>touch*/ Modernizr['touch'] = ('ontouchstart' in window) || hash['touch'].offsetTop === 9; /*>>touch*/
  213. /*>>csstransforms3d*/ Modernizr['csstransforms3d'] = hash['csstransforms3d'].offsetLeft === 9; /*>>csstransforms3d*/
  214. /*>>generatedcontent*/Modernizr['generatedcontent'] = hash['generatedcontent'].offsetHeight >= 1; /*>>generatedcontent*/
  215. /*>>fontface*/ Modernizr['fontface'] = /src/i.test(cssText) &&
  216. cssText.indexOf(rule.split(' ')[0]) === 0; /*>>fontface*/
  217. }, len, tests);
  218. })([
  219. // Pass in styles to be injected into document
  220. /*>>fontface*/ '@font-face {font-family:"font";src:url("https://")}' /*>>fontface*/
  221. /*>>touch*/ ,['@media (',prefixes.join('touch-enabled),('),mod,')',
  222. '{#touch{top:9px;position:absolute}}'].join('') /*>>touch*/
  223. /*>>csstransforms3d*/ ,['@media (',prefixes.join('transform-3d),('),mod,')',
  224. '{#csstransforms3d{left:9px;position:absolute}}'].join('')/*>>csstransforms3d*/
  225. /*>>generatedcontent*/,['#generatedcontent:after{content:"',smile,'";visibility:hidden}'].join('') /*>>generatedcontent*/
  226. ],
  227. [
  228. /*>>fontface*/ 'fontface' /*>>fontface*/
  229. /*>>touch*/ ,'touch' /*>>touch*/
  230. /*>>csstransforms3d*/ ,'csstransforms3d' /*>>csstransforms3d*/
  231. /*>>generatedcontent*/,'generatedcontent' /*>>generatedcontent*/
  232. ]);/*>>testBundle*/
  233. /**
  234. * Tests
  235. * -----
  236. */
  237. tests['flexbox'] = function() {
  238. /**
  239. * setPrefixedValueCSS sets the property of a specified element
  240. * adding vendor prefixes to the VALUE of the property.
  241. * @param {Element} element
  242. * @param {string} property The property name. This will not be prefixed.
  243. * @param {string} value The value of the property. This WILL be prefixed.
  244. * @param {string=} extra Additional CSS to append unmodified to the end of
  245. * the CSS string.
  246. */
  247. function setPrefixedValueCSS( element, property, value, extra ) {
  248. property += ':';
  249. element.style.cssText = (property + prefixes.join(value + ';' + property)).slice(0, -property.length) + (extra || '');
  250. }
  251. /**
  252. * setPrefixedPropertyCSS sets the property of a specified element
  253. * adding vendor prefixes to the NAME of the property.
  254. * @param {Element} element
  255. * @param {string} property The property name. This WILL be prefixed.
  256. * @param {string} value The value of the property. This will not be prefixed.
  257. * @param {string=} extra Additional CSS to append unmodified to the end of
  258. * the CSS string.
  259. */
  260. function setPrefixedPropertyCSS( element, property, value, extra ) {
  261. element.style.cssText = prefixes.join(property + ':' + value + ';') + (extra || '');
  262. }
  263. var c = document.createElement('div'),
  264. elem = document.createElement('div');
  265. setPrefixedValueCSS(c, 'display', 'box', 'width:42px;padding:0;');
  266. setPrefixedPropertyCSS(elem, 'box-flex', '1', 'width:10px;');
  267. c.appendChild(elem);
  268. docElement.appendChild(c);
  269. var ret = elem.offsetWidth === 42;
  270. c.removeChild(elem);
  271. docElement.removeChild(c);
  272. return ret;
  273. };
  274. // On the S60 and BB Storm, getContext exists, but always returns undefined
  275. // http://github.com/Modernizr/Modernizr/issues/issue/97/
  276. tests['canvas'] = function() {
  277. var elem = document.createElement('canvas');
  278. return !!(elem.getContext && elem.getContext('2d'));
  279. };
  280. tests['canvastext'] = function() {
  281. return !!(Modernizr['canvas'] && is(document.createElement('canvas').getContext('2d').fillText, 'function'));
  282. };
  283. // This WebGL test may false positive.
  284. // But really it's quite impossible to know whether webgl will succeed until after you create the context.
  285. // You might have hardware that can support a 100x100 webgl canvas, but will not support a 1000x1000 webgl
  286. // canvas. So this feature inference is weak, but intentionally so.
  287. // It is known to false positive in FF4 with certain hardware and the iPad 2.
  288. tests['webgl'] = function() {
  289. return !!window.WebGLRenderingContext;
  290. };
  291. /*
  292. * The Modernizr.touch test only indicates if the browser supports
  293. * touch events, which does not necessarily reflect a touchscreen
  294. * device, as evidenced by tablets running Windows 7 or, alas,
  295. * the Palm Pre / WebOS (touch) phones.
  296. *
  297. * Additionally, Chrome (desktop) used to lie about its support on this,
  298. * but that has since been rectified: http://crbug.com/36415
  299. *
  300. * We also test for Firefox 4 Multitouch Support.
  301. *
  302. * For more info, see: http://modernizr.github.com/Modernizr/touch.html
  303. */
  304. tests['touch'] = function() {
  305. return Modernizr['touch'];
  306. };
  307. /**
  308. * geolocation tests for the new Geolocation API specification.
  309. * This test is a standards compliant-only test; for more complete
  310. * testing, including a Google Gears fallback, please see:
  311. * http://code.google.com/p/geo-location-javascript/
  312. * or view a fallback solution using google's geo API:
  313. * http://gist.github.com/366184
  314. */
  315. tests['geolocation'] = function() {
  316. return !!navigator.geolocation;
  317. };
  318. // Per 1.6:
  319. // This used to be Modernizr.crosswindowmessaging but the longer
  320. // name has been deprecated in favor of a shorter and property-matching one.
  321. // The old API is still available in 1.6, but as of 2.0 will throw a warning,
  322. // and in the first release thereafter disappear entirely.
  323. tests['postmessage'] = function() {
  324. return !!window.postMessage;
  325. };
  326. // Web SQL database detection is tricky:
  327. // In chrome incognito mode, openDatabase is truthy, but using it will
  328. // throw an exception: http://crbug.com/42380
  329. // We can create a dummy database, but there is no way to delete it afterwards.
  330. // Meanwhile, Safari users can get prompted on any database creation.
  331. // If they do, any page with Modernizr will give them a prompt:
  332. // http://github.com/Modernizr/Modernizr/issues/closed#issue/113
  333. // We have chosen to allow the Chrome incognito false positive, so that Modernizr
  334. // doesn't litter the web with these test databases. As a developer, you'll have
  335. // to account for this gotcha yourself.
  336. tests['websqldatabase'] = function() {
  337. var result = !!window.openDatabase;
  338. /* if (result){
  339. try {
  340. result = !!openDatabase( mod + "testdb", "1.0", mod + "testdb", 2e4);
  341. } catch(e) {
  342. }
  343. } */
  344. return result;
  345. };
  346. // Vendors had inconsistent prefixing with the experimental Indexed DB:
  347. // - Webkit's implementation is accessible through webkitIndexedDB
  348. // - Firefox shipped moz_indexedDB before FF4b9, but since then has been mozIndexedDB
  349. // For speed, we don't test the legacy (and beta-only) indexedDB
  350. tests['indexedDB'] = function() {
  351. for ( var i = -1, len = domPrefixes.length; ++i < len; ){
  352. if ( window[domPrefixes[i].toLowerCase() + 'IndexedDB'] ){
  353. return true;
  354. }
  355. }
  356. return !!window.indexedDB;
  357. };
  358. // documentMode logic from YUI to filter out IE8 Compat Mode
  359. // which false positives.
  360. tests['hashchange'] = function() {
  361. return isEventSupported('hashchange', window) && (document.documentMode === undefined || document.documentMode > 7);
  362. };
  363. // Per 1.6:
  364. // This used to be Modernizr.historymanagement but the longer
  365. // name has been deprecated in favor of a shorter and property-matching one.
  366. // The old API is still available in 1.6, but as of 2.0 will throw a warning,
  367. // and in the first release thereafter disappear entirely.
  368. tests['history'] = function() {
  369. return !!(window.history && history.pushState);
  370. };
  371. tests['draganddrop'] = function() {
  372. return isEventSupported('dragstart') && isEventSupported('drop');
  373. };
  374. // Mozilla is targeting to land MozWebSocket for FF6
  375. // bugzil.la/659324
  376. tests['websockets'] = function() {
  377. for ( var i = -1, len = domPrefixes.length; ++i < len; ){
  378. if ( window[domPrefixes[i] + 'WebSocket'] ){
  379. return true;
  380. }
  381. }
  382. return 'WebSocket' in window;
  383. };
  384. // http://css-tricks.com/rgba-browser-support/
  385. tests['rgba'] = function() {
  386. // Set an rgba() color and check the returned value
  387. setCss('background-color:rgba(150,255,150,.5)');
  388. return contains(mStyle.backgroundColor, 'rgba');
  389. };
  390. tests['hsla'] = function() {
  391. // Same as rgba(), in fact, browsers re-map hsla() to rgba() internally,
  392. // except IE9 who retains it as hsla
  393. setCss('background-color:hsla(120,40%,100%,.5)');
  394. return contains(mStyle.backgroundColor, 'rgba') || contains(mStyle.backgroundColor, 'hsla');
  395. };
  396. tests['multiplebgs'] = function() {
  397. // Setting multiple images AND a color on the background shorthand property
  398. // and then querying the style.background property value for the number of
  399. // occurrences of "url(" is a reliable method for detecting ACTUAL support for this!
  400. setCss('background:url(https://),url(https://),red url(https://)');
  401. // If the UA supports multiple backgrounds, there should be three occurrences
  402. // of the string "url(" in the return value for elemStyle.background
  403. return /(url\s*\(.*?){3}/.test(mStyle.background);
  404. };
  405. // In testing support for a given CSS property, it's legit to test:
  406. // `elem.style[styleName] !== undefined`
  407. // If the property is supported it will return an empty string,
  408. // if unsupported it will return undefined.
  409. // We'll take advantage of this quick test and skip setting a style
  410. // on our modernizr element, but instead just testing undefined vs
  411. // empty string.
  412. tests['backgroundsize'] = function() {
  413. return testPropsAll('backgroundSize');
  414. };
  415. tests['borderimage'] = function() {
  416. return testPropsAll('borderImage');
  417. };
  418. // Super comprehensive table about all the unique implementations of
  419. // border-radius: http://muddledramblings.com/table-of-css3-border-radius-compliance
  420. tests['borderradius'] = function() {
  421. return testPropsAll('borderRadius');
  422. };
  423. // WebOS unfortunately false positives on this test.
  424. tests['boxshadow'] = function() {
  425. return testPropsAll('boxShadow');
  426. };
  427. // FF3.0 will false positive on this test
  428. tests['textshadow'] = function() {
  429. return document.createElement('div').style.textShadow === '';
  430. };
  431. tests['opacity'] = function() {
  432. // Browsers that actually have CSS Opacity implemented have done so
  433. // according to spec, which means their return values are within the
  434. // range of [0.0,1.0] - including the leading zero.
  435. setCssAll('opacity:.55');
  436. // The non-literal . in this regex is intentional:
  437. // German Chrome returns this value as 0,55
  438. // https://github.com/Modernizr/Modernizr/issues/#issue/59/comment/516632
  439. return /^0.55$/.test(mStyle.opacity);
  440. };
  441. tests['cssanimations'] = function() {
  442. return testPropsAll('animationName');
  443. };
  444. tests['csscolumns'] = function() {
  445. return testPropsAll('columnCount');
  446. };
  447. tests['cssgradients'] = function() {
  448. /**
  449. * For CSS Gradients syntax, please see:
  450. * http://webkit.org/blog/175/introducing-css-gradients/
  451. * https://developer.mozilla.org/en/CSS/-moz-linear-gradient
  452. * https://developer.mozilla.org/en/CSS/-moz-radial-gradient
  453. * http://dev.w3.org/csswg/css3-images/#gradients-
  454. */
  455. var str1 = 'background-image:',
  456. str2 = 'gradient(linear,left top,right bottom,from(#9f9),to(white));',
  457. str3 = 'linear-gradient(left top,#9f9, white);';
  458. setCss(
  459. (str1 + prefixes.join(str2 + str1) + prefixes.join(str3 + str1)).slice(0, -str1.length)
  460. );
  461. return contains(mStyle.backgroundImage, 'gradient');
  462. };
  463. tests['cssreflections'] = function() {
  464. return testPropsAll('boxReflect');
  465. };
  466. tests['csstransforms'] = function() {
  467. return !!testProps(['transformProperty', 'WebkitTransform', 'MozTransform', 'OTransform', 'msTransform']);
  468. };
  469. tests['csstransforms3d'] = function() {
  470. var ret = !!testProps(['perspectiveProperty', 'WebkitPerspective', 'MozPerspective', 'OPerspective', 'msPerspective']);
  471. // Webkit’s 3D transforms are passed off to the browser's own graphics renderer.
  472. // It works fine in Safari on Leopard and Snow Leopard, but not in Chrome in
  473. // some conditions. As a result, Webkit typically recognizes the syntax but
  474. // will sometimes throw a false positive, thus we must do a more thorough check:
  475. if ( ret && 'webkitPerspective' in docElement.style ) {
  476. // Webkit allows this media query to succeed only if the feature is enabled.
  477. // `@media (transform-3d),(-o-transform-3d),(-moz-transform-3d),(-ms-transform-3d),(-webkit-transform-3d),(modernizr){ ... }`
  478. ret = Modernizr['csstransforms3d'];
  479. }
  480. return ret;
  481. };
  482. tests['csstransitions'] = function() {
  483. return testPropsAll('transitionProperty');
  484. };
  485. /*>>fontface*/
  486. // @font-face detection routine by Diego Perini
  487. // http://javascript.nwbox.com/CSSSupport/
  488. tests['fontface'] = function() {
  489. return Modernizr['fontface'];
  490. };
  491. /*>>fontface*/
  492. // CSS generated content detection
  493. tests['generatedcontent'] = function() {
  494. return Modernizr['generatedcontent'];
  495. };
  496. // These tests evaluate support of the video/audio elements, as well as
  497. // testing what types of content they support.
  498. //
  499. // We're using the Boolean constructor here, so that we can extend the value
  500. // e.g. Modernizr.video // true
  501. // Modernizr.video.ogg // 'probably'
  502. //
  503. // Codec values from : http://github.com/NielsLeenheer/html5test/blob/9106a8/index.html#L845
  504. // thx to NielsLeenheer and zcorpan
  505. // Note: in FF 3.5.1 and 3.5.0, "no" was a return value instead of empty string.
  506. // Modernizr does not normalize for that.
  507. tests['video'] = function() {
  508. var elem = document.createElement('video'),
  509. bool = false;
  510. // IE9 Running on Windows Server SKU can cause an exception to be thrown, bug #224
  511. try {
  512. if ( bool = !!elem.canPlayType ) {
  513. bool = new Boolean(bool);
  514. bool.ogg = elem.canPlayType('video/ogg; codecs="theora"');
  515. // Workaround required for IE9, which doesn't report video support without audio codec specified.
  516. // bug 599718 @ msft connect
  517. var h264 = 'video/mp4; codecs="avc1.42E01E';
  518. bool.h264 = elem.canPlayType(h264 + '"') || elem.canPlayType(h264 + ', mp4a.40.2"');
  519. bool.webm = elem.canPlayType('video/webm; codecs="vp8, vorbis"');
  520. }
  521. } catch(e) { }
  522. return bool;
  523. };
  524. tests['audio'] = function() {
  525. var elem = document.createElement('audio'),
  526. bool = false;
  527. try {
  528. if ( bool = !!elem.canPlayType ) {
  529. bool = new Boolean(bool);
  530. bool.ogg = elem.canPlayType('audio/ogg; codecs="vorbis"');
  531. bool.mp3 = elem.canPlayType('audio/mpeg;');
  532. // Mimetypes accepted:
  533. // https://developer.mozilla.org/En/Media_formats_supported_by_the_audio_and_video_elements
  534. // http://bit.ly/iphoneoscodecs
  535. bool.wav = elem.canPlayType('audio/wav; codecs="1"');
  536. bool.m4a = elem.canPlayType('audio/x-m4a;') || elem.canPlayType('audio/aac;');
  537. }
  538. } catch(e) { }
  539. return bool;
  540. };
  541. // Firefox has made these tests rather unfun.
  542. // In FF4, if disabled, window.localStorage should === null.
  543. // Normally, we could not test that directly and need to do a
  544. // `('localStorage' in window) && ` test first because otherwise Firefox will
  545. // throw http://bugzil.la/365772 if cookies are disabled
  546. // However, in Firefox 4 betas, if dom.storage.enabled == false, just mentioning
  547. // the property will throw an exception. http://bugzil.la/599479
  548. // This looks to be fixed for FF4 Final.
  549. // Because we are forced to try/catch this, we'll go aggressive.
  550. // FWIW: IE8 Compat mode supports these features completely:
  551. // http://www.quirksmode.org/dom/html5.html
  552. // But IE8 doesn't support either with local files
  553. tests['localstorage'] = function() {
  554. try {
  555. return !!localStorage.getItem;
  556. } catch(e) {
  557. return false;
  558. }
  559. };
  560. tests['sessionstorage'] = function() {
  561. try {
  562. return !!sessionStorage.getItem;
  563. } catch(e){
  564. return false;
  565. }
  566. };
  567. tests['webworkers'] = function() {
  568. return !!window.Worker;
  569. };
  570. tests['applicationcache'] = function() {
  571. return !!window.applicationCache;
  572. };
  573. // Thanks to Erik Dahlstrom
  574. tests['svg'] = function() {
  575. return !!document.createElementNS && !!document.createElementNS(ns.svg, 'svg').createSVGRect;
  576. };
  577. // specifically for SVG inline in HTML, not within XHTML
  578. // test page: paulirish.com/demo/inline-svg
  579. tests['inlinesvg'] = function() {
  580. var div = document.createElement('div');
  581. div.innerHTML = '<svg/>';
  582. return (div.firstChild && div.firstChild.namespaceURI) == ns.svg;
  583. };
  584. // Thanks to F1lt3r and lucideer, ticket #35
  585. tests['smil'] = function() {
  586. return !!document.createElementNS && /SVG/.test(toString.call(document.createElementNS(ns.svg, 'animate')));
  587. };
  588. tests['svgclippaths'] = function() {
  589. // Possibly returns a false positive in Safari 3.2?
  590. return !!document.createElementNS && /SVG/.test(toString.call(document.createElementNS(ns.svg, 'clipPath')));
  591. };
  592. // input features and input types go directly onto the ret object, bypassing the tests loop.
  593. // Hold this guy to execute in a moment.
  594. function webforms() {
  595. // Run through HTML5's new input attributes to see if the UA understands any.
  596. // We're using f which is the <input> element created early on
  597. // Mike Taylr has created a comprehensive resource for testing these attributes
  598. // when applied to all input types:
  599. // http://miketaylr.com/code/input-type-attr.html
  600. // spec: http://www.whatwg.org/specs/web-apps/current-work/multipage/the-input-element.html#input-type-attr-summary
  601. // Only input placeholder is tested while textarea's placeholder is not.
  602. // Currently Safari 4 and Opera 11 have support only for the input placeholder
  603. // Both tests are available in feature-detects/forms-placeholder.js
  604. Modernizr['input'] = (function( props ) {
  605. for ( var i = 0, len = props.length; i < len; i++ ) {
  606. attrs[ props[i] ] = !!(props[i] in inputElem);
  607. }
  608. return attrs;
  609. })('autocomplete autofocus list placeholder max min multiple pattern required step'.split(' '));
  610. // Run through HTML5's new input types to see if the UA understands any.
  611. // This is put behind the tests runloop because it doesn't return a
  612. // true/false like all the other tests; instead, it returns an object
  613. // containing each input type with its corresponding true/false value
  614. // Big thanks to @miketaylr for the html5 forms expertise. http://miketaylr.com/
  615. Modernizr['inputtypes'] = (function(props) {
  616. for ( var i = 0, bool, inputElemType, defaultView, len = props.length; i < len; i++ ) {
  617. inputElem.setAttribute('type', inputElemType = props[i]);
  618. bool = inputElem.type !== 'text';
  619. // We first check to see if the type we give it sticks..
  620. // If the type does, we feed it a textual value, which shouldn't be valid.
  621. // If the value doesn't stick, we know there's input sanitization which infers a custom UI
  622. if ( bool ) {
  623. inputElem.value = smile;
  624. inputElem.style.cssText = 'position:absolute;visibility:hidden;';
  625. if ( /^range$/.test(inputElemType) && inputElem.style.WebkitAppearance !== undefined ) {
  626. docElement.appendChild(inputElem);
  627. defaultView = document.defaultView;
  628. // Safari 2-4 allows the smiley as a value, despite making a slider
  629. bool = defaultView.getComputedStyle &&
  630. defaultView.getComputedStyle(inputElem, null).WebkitAppearance !== 'textfield' &&
  631. // Mobile android web browser has false positive, so must
  632. // check the height to see if the widget is actually there.
  633. (inputElem.offsetHeight !== 0);
  634. docElement.removeChild(inputElem);
  635. } else if ( /^(search|tel)$/.test(inputElemType) ){
  636. // Spec doesnt define any special parsing or detectable UI
  637. // behaviors so we pass these through as true
  638. // Interestingly, opera fails the earlier test, so it doesn't
  639. // even make it here.
  640. } else if ( /^(url|email)$/.test(inputElemType) ) {
  641. // Real url and email support comes with prebaked validation.
  642. bool = inputElem.checkValidity && inputElem.checkValidity() === false;
  643. } else if ( /^color$/.test(inputElemType) ) {
  644. // chuck into DOM and force reflow for Opera bug in 11.00
  645. // github.com/Modernizr/Modernizr/issues#issue/159
  646. docElement.appendChild(inputElem);
  647. docElement.offsetWidth;
  648. bool = inputElem.value != smile;
  649. docElement.removeChild(inputElem);
  650. } else {
  651. // If the upgraded input compontent rejects the :) text, we got a winner
  652. bool = inputElem.value != smile;
  653. }
  654. }
  655. inputs[ props[i] ] = !!bool;
  656. }
  657. return inputs;
  658. })('search tel url email datetime date month week time datetime-local number range color'.split(' '));
  659. }
  660. // End of test definitions
  661. // -----------------------
  662. // Run through all tests and detect their support in the current UA.
  663. // todo: hypothetically we could be doing an array of tests and use a basic loop here.
  664. for ( var feature in tests ) {
  665. if ( hasOwnProperty(tests, feature) ) {
  666. // run the test, throw the return value into the Modernizr,
  667. // then based on that boolean, define an appropriate className
  668. // and push it into an array of classes we'll join later.
  669. featureName = feature.toLowerCase();
  670. Modernizr[featureName] = tests[feature]();
  671. classes.push((Modernizr[featureName] ? '' : 'no-') + featureName);
  672. }
  673. }
  674. // input tests need to run.
  675. Modernizr.input || webforms();
  676. /**
  677. * addTest allows the user to define their own feature tests
  678. * the result will be added onto the Modernizr object,
  679. * as well as an appropriate className set on the html element
  680. *
  681. * @param feature - String naming the feature
  682. * @param test - Function returning true if feature is supported, false if not
  683. */
  684. Modernizr.addTest = function ( feature, test ) {
  685. if ( typeof feature == "object" ) {
  686. for ( var key in feature ) {
  687. if ( hasOwnProperty( feature, key ) ) {
  688. Modernizr.addTest( key, feature[ key ] );
  689. }
  690. }
  691. } else {
  692. feature = feature.toLowerCase();
  693. if ( Modernizr[feature] !== undefined ) {
  694. // we're going to quit if you're trying to overwrite an existing test
  695. // if we were to allow it, we'd do this:
  696. // var re = new RegExp("\\b(no-)?" + feature + "\\b");
  697. // docElement.className = docElement.className.replace( re, '' );
  698. // but, no rly, stuff 'em.
  699. return;
  700. }
  701. test = typeof test == "boolean" ? test : !!test();
  702. docElement.className += ' ' + (test ? '' : 'no-') + feature;
  703. Modernizr[feature] = test;
  704. }
  705. return Modernizr; // allow chaining.
  706. };
  707. // Reset modElem.cssText to nothing to reduce memory footprint.
  708. setCss('');
  709. modElem = inputElem = null;
  710. //>>BEGIN IEPP
  711. // Enable HTML 5 elements for styling (and printing) in IE.
  712. if ( window.attachEvent && (function(){ var elem = document.createElement('div');
  713. elem.innerHTML = '<elem></elem>';
  714. return elem.childNodes.length !== 1; })() ) {
  715. // iepp v2 by @jon_neal & afarkas : github.com/aFarkas/iepp/
  716. (function(win, doc) {
  717. win.iepp = win.iepp || {};
  718. var iepp = win.iepp,
  719. elems = iepp.html5elements || 'abbr|article|aside|audio|canvas|datalist|details|figcaption|figure|footer|header|hgroup|mark|meter|nav|output|progress|section|summary|time|video',
  720. elemsArr = elems.split('|'),
  721. elemsArrLen = elemsArr.length,
  722. elemRegExp = new RegExp('(^|\\s)('+elems+')', 'gi'),
  723. tagRegExp = new RegExp('<(\/*)('+elems+')', 'gi'),
  724. filterReg = /^\s*[\{\}]\s*$/,
  725. ruleRegExp = new RegExp('(^|[^\\n]*?\\s)('+elems+')([^\\n]*)({[\\n\\w\\W]*?})', 'gi'),
  726. docFrag = doc.createDocumentFragment(),
  727. html = doc.documentElement,
  728. head = html.firstChild,
  729. bodyElem = doc.createElement('body'),
  730. styleElem = doc.createElement('style'),
  731. printMedias = /print|all/,
  732. body;
  733. function shim(doc) {
  734. var a = -1;
  735. while (++a < elemsArrLen)
  736. // Use createElement so IE allows HTML5-named elements in a document
  737. doc.createElement(elemsArr[a]);
  738. }
  739. iepp.getCSS = function(styleSheetList, mediaType) {
  740. if(styleSheetList+'' === undefined){return '';}
  741. var a = -1,
  742. len = styleSheetList.length,
  743. styleSheet,
  744. cssTextArr = [];
  745. while (++a < len) {
  746. styleSheet = styleSheetList[a];
  747. //currently no test for disabled/alternate stylesheets
  748. if(styleSheet.disabled){continue;}
  749. mediaType = styleSheet.media || mediaType;
  750. // Get css from all non-screen stylesheets and their imports
  751. if (printMedias.test(mediaType)) cssTextArr.push(iepp.getCSS(styleSheet.imports, mediaType), styleSheet.cssText);
  752. //reset mediaType to all with every new *not imported* stylesheet
  753. mediaType = 'all';
  754. }
  755. return cssTextArr.join('');
  756. };
  757. iepp.parseCSS = function(cssText) {
  758. var cssTextArr = [],
  759. rule;
  760. while ((rule = ruleRegExp.exec(cssText)) != null){
  761. // Replace all html5 element references with iepp substitute classnames
  762. cssTextArr.push(( (filterReg.exec(rule[1]) ? '\n' : rule[1]) +rule[2]+rule[3]).replace(elemRegExp, '$1.iepp_$2')+rule[4]);
  763. }
  764. return cssTextArr.join('\n');
  765. };
  766. iepp.writeHTML = function() {
  767. var a = -1;
  768. body = body || doc.body;
  769. while (++a < elemsArrLen) {
  770. var nodeList = doc.getElementsByTagName(elemsArr[a]),
  771. nodeListLen = nodeList.length,
  772. b = -1;
  773. while (++b < nodeListLen)
  774. if (nodeList[b].className.indexOf('iepp_') < 0)
  775. // Append iepp substitute classnames to all html5 elements
  776. nodeList[b].className += ' iepp_'+elemsArr[a];
  777. }
  778. docFrag.appendChild(body);
  779. html.appendChild(bodyElem);
  780. // Write iepp substitute print-safe document
  781. bodyElem.className = body.className;
  782. bodyElem.id = body.id;
  783. // Replace HTML5 elements with <font> which is print-safe and shouldn't conflict since it isn't part of html5
  784. bodyElem.innerHTML = body.innerHTML.replace(tagRegExp, '<$1font');
  785. };
  786. iepp._beforePrint = function() {
  787. // Write iepp custom print CSS
  788. styleElem.styleSheet.cssText = iepp.parseCSS(iepp.getCSS(doc.styleSheets, 'all'));
  789. iepp.writeHTML();
  790. };
  791. iepp.restoreHTML = function(){
  792. // Undo everything done in onbeforeprint
  793. bodyElem.innerHTML = '';
  794. html.removeChild(bodyElem);
  795. html.appendChild(body);
  796. };
  797. iepp._afterPrint = function(){
  798. // Undo everything done in onbeforeprint
  799. iepp.restoreHTML();
  800. styleElem.styleSheet.cssText = '';
  801. };
  802. // Shim the document and iepp fragment
  803. shim(doc);
  804. shim(docFrag);
  805. //
  806. if(iepp.disablePP){return;}
  807. // Add iepp custom print style element
  808. head.insertBefore(styleElem, head.firstChild);
  809. styleElem.media = 'print';
  810. styleElem.className = 'iepp-printshim';
  811. win.attachEvent(
  812. 'onbeforeprint',
  813. iepp._beforePrint
  814. );
  815. win.attachEvent(
  816. 'onafterprint',
  817. iepp._afterPrint
  818. );
  819. })(window, document);
  820. }
  821. //>>END IEPP
  822. // Assign private properties to the return object with prefix
  823. Modernizr._version = version;
  824. // expose these for the plugin API. Look in the source for how to join() them against your input
  825. Modernizr._prefixes = prefixes;
  826. Modernizr._domPrefixes = domPrefixes;
  827. // Modernizr.mq tests a given media query, live against the current state of the window
  828. // A few important notes:
  829. // * If a browser does not support media queries at all (eg. oldIE) the mq() will always return false
  830. // * A max-width or orientation query will be evaluated against the current state, which may change later.
  831. // * You must specify values. Eg. If you are testing support for the min-width media query use:
  832. // Modernizr.mq('(min-width:0)')
  833. // usage:
  834. // Modernizr.mq('only screen and (max-width:768)')
  835. Modernizr.mq = testMediaQuery;
  836. // Modernizr.hasEvent() detects support for a given event, with an optional element to test on
  837. // Modernizr.hasEvent('gesturestart', elem)
  838. Modernizr.hasEvent = isEventSupported;
  839. // Modernizr.testProp() investigates whether a given style property is recognized
  840. // Note that the property names must be provided in the camelCase variant.
  841. // Modernizr.testProp('pointerEvents')
  842. Modernizr.testProp = function(prop){
  843. return testProps([prop]);
  844. };
  845. // Modernizr.testAllProps() investigates whether a given style property,
  846. // or any of its vendor-prefixed variants, is recognized
  847. // Note that the property names must be provided in the camelCase variant.
  848. // Modernizr.testAllProps('boxSizing')
  849. Modernizr.testAllProps = testPropsAll;
  850. // Modernizr.testStyles() allows you to add custom styles to the document and test an element afterwards
  851. // Modernizr.testStyles('#modernizr { position:absolute }', function(elem, rule){ ... })
  852. Modernizr.testStyles = injectElementWithStyles;
  853. // Modernizr.prefixed() returns the prefixed or nonprefixed property name variant of your input
  854. // Modernizr.prefixed('boxSizing') // 'MozBoxSizing'
  855. // Properties must be passed as dom-style camelcase, rather than `box-sizing` hypentated style.
  856. // Return values will also be the camelCase variant, if you need to translate that to hypenated style use:
  857. //
  858. // str.replace(/([A-Z])/g, function(str,m1){ return '-' + m1.toLowerCase(); }).replace(/^ms-/,'-ms-');
  859. // If you're trying to ascertain which transition end event to bind to, you might do something like...
  860. //
  861. // var transEndEventNames = {
  862. // 'WebkitTransition' : 'webkitTransitionEnd',
  863. // 'MozTransition' : 'transitionend',
  864. // 'OTransition' : 'oTransitionEnd',
  865. // 'msTransition' : 'msTransitionEnd', // maybe?
  866. // 'transition' : 'transitionEnd'
  867. // },
  868. // transEndEventName = transEndEventNames[ Modernizr.prefixed('transition') ];
  869. Modernizr.prefixed = function(prop){
  870. return testPropsAll(prop, 'pfx');
  871. };
  872. // Remove "no-js" class from <html> element, if it exists:
  873. docElement.className = docElement.className.replace(/\bno-js\b/, '')
  874. // Add the new classes to the <html> element.
  875. + (enableClasses ? ' js ' + classes.join(' ') : '');
  876. return Modernizr;
  877. })(this, this.document);