Modernizr: практическое применение
Укажи галочками те технологии, тесты которых собираешься проводить, затем создай свою персональную версию библиотеки кнопкой «Generate». Если проставить все галочки, получившегося кода хватит на пару экранов небольшого ноутбука – всего 15 КБ.
Затем просто подключи его к своей странице и проверь, как оно. Если всё работает, у элемента HTML должны появиться многочисленные классы:
Думаю, фантазия опытного верстальщика подскажет примеры более красочные и развёрнутые.
Тесты
yep – подключаю сценарий, использующий геолокационные возможности браузера.
nope – пытаюсь обойтись без них в geo-polyfill.js.
Говорят, что вот так тоже можно делать:
Вот пример посложнее:
Не так уж и сложно, верно?
и не придирайтесь к слову “поли-заполнитель” – MicroSoft отлично его перевели.
Одна из крутых возможностей Modernizr.load – возможность выстроить подключаемые сценарии в очередь. Многим это может ни о чём не говорить, но пользователи HTML5 Boilerplate скорее всего знакомы с запасным jQuery из Google CDN. Выглядит как-то так:
Работает так: сначала пытается загрузить jQuery в сценарии, а затем – сразу же после, проверяя, что объект jQuery доступен. Если нет, то пытается загрузить локальную копию jQuery. Это не так-то уж и просто, и Modernizr.load спешит на помощь. Следуй вот такой логике, и он возьмёт в свои руки порядок подключения сценариев:
Замечание: используй этот метод лишь для откатов, потому как последовательная загрузка сценариев вместо параллельной может сильно ударить по быстродействию.
Расширяемость
В документации есть раздел «Extensibility», посвящённый расширяемости, где всё подробно описано. А в проекте на GitHub’е есть папка, куда складывают все годные пользовательские расширения: /feature-detects/.
Поддержка браузеров
IE6+, Firefox 3.5+, Opera 9.6+, Safari 2+, Chrome. На мобильных устройствах – Mobile Safari на iOS, Webkit на Android’s, Opera Mobile, Firefox Mobile и есть большие надежды на поддержку Blackberry 6+.
Заключение
Отличное подспорье для проектов с плюс-минус широкой аудиторией, когда хорошая поддержка важнее времени загрузки и исполнения страницы. Впрочем, если знать меру – можно и на простые одностраничные сайты его вешать, просто для удобства или даже за делом.
Modernizr используют в довольно крупных компаниях: twitter, Google, Microsoft.
Использование Modernizr 3.0. Краткий обзор
Дата публикации: 2015-11-04
От автора: браузеры становятся все быстрее, принимаются новые стандарты, но на деле у нас просто не остается выбора – нам приходится поддерживать старые версии браузеров. Вкратце, нам нужно использование библиотеки Modernizr.
Modernizr – что это? Это JavaScript библиотека, которая сканирует браузер на поддержку тех или иных свойств, и все доступные свойства помечаются в теге html в качестве классов или в качестве свойств объекта Modernizr. Недавно библиотека получила несколько крупных обновлений с новыми свойствами, изменениями и улучшениями. В этой статье мы по новой изучим Modernizr. Взглянем, что нам может предложить версия 3.0!
Скачиваем Modernizr
Предыдущие версии были доступны как в тестовых сборках (неминифицированные версии) так и с пользовательскими настойками. Можно было выбрать отдельные свойства и API. Скачать библиотеку можно на странице загрузки. В Modernizr 3 появилась командная строка CLI, через нее можно сделать все то же самое, что и в прошлых версиях. Сначала выберите свойства, которые вам потребуются. Также опционально можно скачать файл конфигурации JSON.
В этом файле описаны настройки, которые определяют выходной файл Modernizr:
Практический курс по верстке адаптивного сайта с нуля!
Изучите курс и узнайте, как верстать современные сайты на HTML5 и CSS3
Modernizr js что это
Modernizr is a small piece of JavaScript code that automatically detects the availability of next-generation web technologies in your user’s browsers. Rather than blacklisting entire ranges of browsers based on “UA sniffing,” Modernizr uses feature detection to allow you to easily tailor your user’s experiences based on the actual capabilities of their browser.
With this knowledge that Modernizr gives you, you can take advantage of these new features in the browsers that can render or utilize them, and still have easy and reliable means of controlling the situation for the browsers that cannot.
What is feature detection?
Downloading Modernizr
A lot has changed since the last version of Modernizr. There no longer is a single, base modernizr.js file. Instead, just head over to the Download page as you could have previously, and select the features you want to use in your project. This way we can provide the smallest file possible, which means a faster website for you. Once you have done that, just hit the Build button and you’ve got your own custom build of Modernizr, hot off the presses!
Command Line Config
Since 3.0, Modernizr also ships its build system as a node module on npm. That means that you can quickly create multiple builds of Modernizr for different projects, without even having to open a new browser tab.
Once you have npm installed, you can install the Modernizr command line tool by running
Now you are ready to get your start making your custom build! You can download the configuration file from the build menu (under «Command Line Config»). This will give you a JSON file that you will give to the Modernizr module to make your custom build.
Note that you will need to give the command line config the file path to the configuration you downloaded from the site. In the above example, we are running the modernizr command from the same folder that we downloaded the modernizr-config.json file to.
Grunt Config
If you do not want to manually run your build from the command line every time you update your site, you also have the option to download a Grunt task to do it for you. This configuration file can be used with grunt-modernizr to automatically build your custom version. Just add it to your Gruntfile, and you are off to the races.
Configuration Options
In addition to the available options and feature detects, there are a handful of additional configuration options.
A string that is added before each CSS class.
Whether or not Modernizr should add its CSS classes at all
See the next section for more information on those options
Using Modernizr with CSS
Modernizr’s classes
classPrefix
enableClasses
Using Modernizr with JavaScript
The Modernizr object
Modernizr keeps track of the results of all of it’s feature detections via the Modernizr object. That means that for each test, a corresponding property will be added. You just have to test for truthiness in your code to figure out what you want to do
Helper methods
Modernizr optionally exposes a number of additional functions, that you can read more about in Modernizr API
Modernizr API
Modernizr.on
Modernizr.on( feature, cb )
Modernizr.addTest
Modernizr.addTest( feature, test )
The most common way of creating your own feature detects is by calling Modernizr.addTest with a string (preferably just lowercase, without any punctuation), and a function you want executed that will return a boolean result
When the above is run, it will set Modernizr.itstuesday to true when it is tuesday, and to false every other day of the week. One thing to notice is that the names of feature detect functions are always lowercased when added to the Modernizr object. That means that Modernizr.itsTuesday will not exist, but Modernizr.itstuesday will. Since we only look at the returned value from any feature detection function, you do not need to actually use a function. For simple detections, just passing in a statement that will return a boolean value works just fine.
Just like before, when the above runs Modernizr.hasjquery will be true if jQuery has been included on the page. Not using a function saves a small amount of overhead for the browser, as well as making your code much more readable. Finally, you also have the ability to pass in an object of feature names and their tests. This is handy if you want to add multiple detections in one go. The keys should always be a string, and the value can be either a boolean or function that returns a boolean.
There is really no difference between the first methods and this one, it is just a convenience to let you write more readable code.
Modernizr.atRule
Modernizr._domPrefixes
Modernizr._domPrefixes is exactly the same as _prefixes, but rather than kebab-case properties, all properties are their Capitalized variant
Modernizr.hasEvent
Modernizr.hasEvent( eventName, [element] )
Modernizr.hasEvent lets you determine if the browser supports a supplied event. By default, it does this detection on a div element
However, you are able to give an object as a second argument to hasEvent to detect an event on something other than a div.
Modernizr.mq
Modernizr.mq allows for you to programmatically check if the current browser window state matches a media query.
Only valid media queries are supported, therefore you must always include values with your media query
If you would just like to test that media queries are supported in general, use
Note that if the browser does not support media queries (e.g. old IE) mq will always return false.
Modernizr.prefixed
Modernizr.prefixed( prop, [obj], [elem] )
Modernizr.prefixed takes a string css value in the DOM style camelCase (as opposed to the css style kebab-case) form and returns the (possibly prefixed) version of that property that the browser actually supports. For example, in older Firefox.
One common use case for prefixed is if you’re trying to determine which transition end event to bind to, you might do something like.
If you want a similar lookup, but in kebab-case, you can use prefixedCSS.
Modernizr.prefixedCSS
Since it is only useful for CSS style properties, it can only be tested against an HTMLElement. Properties can be passed as both the DOM style camelCase or CSS style kebab-case.
Modernizr.prefixedCSSValue
Modernizr.prefixedCSSValue( prop, value )
Modernizr._prefixes
Modernizr._prefixes is the internal list of prefixes that we test against inside of things like prefixed and prefixedCSS. It is simply an array of kebab-case vendor prefixes you can use within your code. Some common use cases include Generating all possible prefixed version of a CSS property
Generating all possible prefixed version of a CSS value
Modernizr.testAllProps
Modernizr.testAllProps( prop, [value], [skipValueTest] )
testAllProps determines whether a given CSS property, in some prefixed form, is supported by the browser.
It can optionally be given a CSS value in string form to test if a property value is valid
A boolean can be passed as a third parameter to skip the value check when native detection (@supports) isn’t available.
Modernizr.testProp
Modernizr.testProp( prop, [value], [useValue] )
Just like testAllProps, only it does not check any vendor prefixed version of the string. Note that the property name must be provided in camelCase (e.g. boxSizing not box-sizing)
You can also provide a value as an optional second argument to check if a specific value is supported
Modernizr.testStyles
Modernizr.testStyles( rule, callback, [nodes], [testnames] )
Modernizr.testStyles takes a CSS rule and injects it onto the current page along with (possibly multiple) DOM elements. This lets you check for features that can not be detected by simply checking the IDL.
If your test requires multiple nodes, you can include a third argument indicating how many additional div elements to include on the page. The additional nodes are injected as children of the elem that is returned as the first argument to the callback.
Features detected by Modernizr
Detects support for the API that provides information about the ambient light levels, as detected by the device’s light detector, in terms of lux units.
Detects support for the Application Cache, for storing data to enable web-based applications run offline.
The API has been heavily criticized and discussions are underway to address this.
Detects the audio element
Detect support for the Battery API, for accessing information about the system’s battery charge level.
Detects support for the Blob constructor, for creating file-like objects of immutable, raw data.
Detects support for the element for 2D drawing.
Detects support for the text APIs for elements.
Detects support for the contenteditable attribute of elements, allowing their DOM text contents to be edited directly by the user.
Detects support for custom context menus.
Detects whether cookie support is enabled.
Detects support for Cross-Origin Resource Sharing: method of performing XMLHttpRequests across domains.
Detects support for the cryptographic functionality available under window.crypto.subtle
Detects support for the Custom Elements API, to create custom html elements via js
Detects support for the window.registerProtocolHandler() API to allow websites to register themselves as possible handlers for particular protocols.
Detects support for CustomEvent.
Detects native support for the Dart programming language.
Detects support for the DataView interface for reading data from an ArrayBuffer as part of the Typed Array spec.
Detects support for emoji character sets.
Detects native support for addEventListener
Detects support for EXIF Orientation in JPEG images.
iOS looks at the EXIF Orientation flag in JPEGs and rotates the image accordingly. Most desktop browsers just ignore this data.
Detects Flash support as well as Flash-blocking plugins
Tests whether the browser supports the detection of Force Touch Events. Force Touch Events allow custom behaviours and interactions to take place based on the given pressure or change in pressure from a compatible trackpad.
Force Touch events are available in OS X 10.11 and later on devices equipped with Force Touch trackpads.
Detects support for the ability to make the current website take over the user’s entire screen
Detects support for the Gamepad API, for access to gamepads and controllers.
Detects support for the Geolocation API for users to provide their location to web applications.
Detects support for the hashchange event, fired when the current location fragment changes.
Detects overlay scrollbars (when scrollbars on overflowed blocks are visible). This is found most commonly on mobile and OS X.
Detects support for the History API for manipulating the browser session history.
Detects support for HTML import, a feature that is used for loading in Web Components.
Detects whether or not the current browser is IE8 in compatibility mode (i.e. acting as IE7).
Detects support for the IndexedDB client-side storage API (final spec).
Detects if the browser can save File/Blob objects to IndexedDB
Detects support for HTML5 element attributes and exposes Boolean subproperties with the results:
There is a custom search event implemented in webkit browsers when using an input[search] element.
Detects support for HTML5 form input types and exposes Boolean subproperties with the results:
Detects support for the Internationalization API which allow easy formatting of number and dates and sorting string based on a locale
Detects native support for JSON handling functions.
Detects support for OpenType ligatures
Detects support for the reversed attribute on the
- element.
Detects support for MathML, for mathematic equations in web pages.
Detects support for Message Channels, a way to communicate between different browsing contexts like iframes, workers, etc..
Detects support for the Notifications API
Detects support for the Page Visibility API, which can be used to disable unnecessary actions and otherwise improve user experience.
Detects support for the Navigation Timing API, for measuring browser and connection performance.
Detects support for the DOM Pointer Events API, which provides a unified event interface for pointing input devices, as implemented in IE10+, Edge and Blink.
Detects support the pointer lock API which allows you to lock the mouse cursor to the browser window.
Detects support for the window.postMessage protocol for cross-document messaging.
Detects support for an API that allows users to get proximity related information from the device’s proximity sensor.
Detects support for querySelector.
Detects the ability to request a specific amount of space for filesystem access
Detects support for the window.requestAnimationFrame API, for offloading animation repainting to the browser for optimized performance.
ServiceWorkers (formerly Navigation Controllers) are a way to persistently cache resources to built apps that work better offline.
Detects support for SVG in or elements.
Template strings are string literals allowing embedded expressions.
Indicates if the browser supports the W3C Touch Events API.
This does not necessarily reflect a touchscreen device:
It’s recommended to bind both mouse and touch/pointer events simultaneously – see this HTML5 Rocks tutorial.
This test will also return true for Firefox 4 Multitouch support.
Detects support for native binary data manipulation via Typed Arrays in JavaScript.
Does not check for DataView support; use Modernizr.dataview for that.
Detects if unicode characters are supported in the current document.
Detects support for IE userData for persisting data, an API similar to localStorage but supported since IE5.
Detects support for the API that provides access to the vibration mechanism of the hosting device, to provide tactile feedback.
Detects support for the video element, as well as testing what types of content it supports.
Detects support for VML.
Detects native support for the Web Intents APIs for service discovery and inter-application communication.
Chrome added support for this in v19, but removed it again in v24 because of «a number of areas for development in both the API and specific user experience in Chrome». No other browsers currently support it, however a JavaScript shim is available.
Detects support for the Web Animation API, a way to create css animations in js
Detects support for XDomainRequest in IE9 & IE8
Detects if an audio element can automatically restart, once it has finished
Detects if audio can be downloaded in the background before it starts playing in the element
Detects the older non standard webaudio API, (as opposed to the standards based AudioContext API)
Enable a developer to remove CPU intensive CSS/JS when battery is low
Detects if Photoshop style blending modes are available in canvas.
Determines if winding rules, which controls if a path can go clockwise or counterclockwise
Detects support for the window.crypto.getRandomValues method for generating cryptographically secure random numbers
Detects support for the all css property, which is a shorthand to reset all css properties (except direction and unicode-bidi) to their original value
Detects whether or not elements can be animated using CSS
Detects support for the appearance css property, which is used to make an element inherit the style of a standard user interface element. It can also be used to remove the default styles of an element, such as input and buttons.
Detects support for CSS Backdrop Filters, allowing for background blur effects like those introduced in iOS 7. Support for this was added to iOS Safari/WebKit in iOS 9.
Detects the ability for the browser to composite backgrounds using blending modes similar to ones found in Photoshop or Illustrator.
Detects the ability to control specifies whether or not an element’s background extends beyond its border in CSS
Detects if you can use the shorthand method to define multiple parts of an element’s background-position simultaniously.
eg background-position: right 10px bottom 10px
Detects the ability to control an element’s background position using css
Detects the ability to use round and space as properties for background-repeat
Method of allowing calculated values for length units. For example:
display: table and table-cell test. (both are tested under one name table-cell )
Tests for CSS.escape() support.
Detects support for the Flexible Box Layout model, a.k.a. Flexbox, which allows easy manipulation of layout order and sizing within a container.
Detects support for the flex-wrap CSS property, part of Flexbox, which isn’t present in all Flexbox implementations (notably Firefox).
This featured in both the ‘tweener’ syntax (implemented by IE10) and the ‘modern’ syntax (implemented by others). This detect will return true for either of these implementations, as long as the flex-wrap property is supported. So to ensure the modern syntax is supported, use together with Modernizr.flexbox :
Detects support for hidpi/retina hairlines, which are CSS borders with less than 1px in width, for being physically 1px on hidpi screens.
Detects support for the ‘:invalid’ CSS pseudo-class.
Detects support for the ‘:nth-child()’ CSS pseudo-selector.
Test for CSS 3 UI «resize» property
Detects support for CSS Snap Points
Detects support for the ‘:target’ CSS pseudo-class.
Detects support for the ‘:valid’ CSS pseudo-class.
Detects support for the will-change css property, which formally signals to the browser that an element will be animating.
Append multiple elements to the DOM within a single insertion.
Does the browser support the HTML5 [hidden] attribute?
Determines if DOM4 MutationObserver support is available.
Detects support for the passive option to addEventListener.
Detect support for the bdi element, a way to have text that is isolated from its possibly bidirectional surroundings
Does the browser support HTML with non-standard / new elements?
Check if browser implements ECMAScript 5 Array per specification.
Check if browser implements ECMAScript 5 Date per specification.
Check if browser implements ECMAScript 5 Function per specification.
Check if browser implements ECMAScript 5 Object per specification.
Check if browser implements everything as specified in ECMAScript 5.
Check if browser implements ECMAScript 5 Object strict mode.
Check if browser implements ECMAScript 5 String per specification.
Check if browser accepts ECMAScript 5 syntax.
Check if browser prevents assignment to global undefined per ECMAScript 5.
Check if browser implements ECMAScript 6 Array per specification.
Check if browser implements ECMAScript 6 Arrow Functions per specification.
Check if browser implements ECMAScript 6 Map, Set, WeakMap and WeakSet
Check if browser implements ECMAScript 6 String.prototype.contains per specification.
Check if browser implements ECMAScript 6 Generators per specification.
Check if browser implements ECMAScript 6 Math per specification.
Check if browser implements ECMAScript 6 Number per specification.
Check if browser implements ECMAScript 6 Object per specification.
Check if browser implements ECMAScript 6 Promises per specification.
Check if browser implements ECMAScript 6 String per specification.
Part of Device Access aspect of HTML5, same category as geolocation.
devicemotion tests for Device Motion Event support, returns boolean value true/false.
deviceorientation tests for Device Orientation Event support, returns boolean value true/false
oninput tests if the browser is able to detect the input event
filereader tests for the File API specification
Tests for objects specific to the File API W3C specification without being redundant (don’t bother testing for Blob since it is assumed to be the File object’s prototype.)
Detects whether input type=»file» is available on the platform
Detects whether input form=»form_id» is available on the platform E.g. IE 10 (and below), don’t support this
Detects whether input type=»number» is capable of receiving and displaying localized numbers, e.g. with comma separator.
Tests for placeholder attribute in inputs and textareas
When used with input[autocomplete] to annotate a form, form.requestAutocomplete() shows a dialog in Chrome that speeds up checkout flows (payments specific for now).
This implementation only tests support for interactive form validation. To check validation for a specific type or a specific other constraint, the test can be combined:
Test for sandbox attribute in iframes.
Test for seamless attribute in iframes.
Test for srcdoc attribute in iframes.
Test for animated png support.
Detects support for the crossOrigin attribute on images, which allow for cross domain images inside of a canvas without tainting it
Test for JPEG 2000 support
Test for JPEG XR support
Test for the sizes attribute on images
Test for the srcset attribute of images
Tests for transparent webp support.
Tests for animated webp support.
Tests for non-alpha lossless webp support.
Tests for lossy, non-alpha webp support.
Tests for all forms of webp support (lossless, lossy, alpha, and animated)..
Modernizr.webp // Basic support (lossy) Modernizr.webp.lossless // Lossless Modernizr.webp.alpha // Alpha (both lossy and lossless) Modernizr.webp.animation // Animated WebP
Detect support for the formaction attribute on form inputs
Detect support for the formenctype attribute on form inputs, which overrides the form enctype attribute
Detect support for the formmethod attribute on form inputs
Detect support for the formtarget attribute on form inputs, which overrides the form target attribute
Detect support for Hover based media queries
Detect support for Pointer based media queries
Detects support for an API that allows for asynchronous transfer of small HTTP data from the client to a server.
Tests for determining low-bandwidth via navigator.connection
There are two iterations of the navigator.connection interface.
The first is present in Android 2.2+ and only in the Browser (not WebView)
The second is specced at http://dev.w3.org/2009/dap/netinfo/ and perhaps landing in WebKit
Unknown devices are assumed as fast
For more rigorous network testing, consider boomerang.js: https://github.com/bluesmoon/boomerang/
Tests for server sent events aka eventsource.
Detects support for the fetch API, a modern replacement for XMLHttpRequest.
Tests for XMLHttpRequest xhr.responseType=’arraybuffer’.
Tests for XMLHttpRequest xhr.responseType=’blob’.
Tests for XMLHttpRequest xhr.responseType=’document’.
Tests for XMLHttpRequest xhr.responseType=’json’.
Tests for XMLHttpRequest xhr.responseType=’text’.
Tests for XMLHttpRequest xhr.responseType.
Detects support for the async attribute on the






