Respond README

The project's README from github.com/scottjehl/Respond. As one markdown file: README.md.

Respond.js

A fast & lightweight polyfill for min/max-width CSS3 Media Queries (for IE 6-8, and more)

The goal of this script is to provide a fast and lightweight (3kb minified / 1kb gzipped) script to enable responsive web designs in browsers that don't support CSS3 Media Queries - in particular, Internet Explorer 8 and under. It's written in such a way that it will probably patch support for other non-supporting browsers as well (more information on that soon).

If you're unfamiliar with the concepts surrounding Responsive Web Design, you can read up here and also here

Demo page (the colors change to show media queries working)

Usage Instructions

  1. Craft your CSS with min/max-width media queries to adapt your layout from mobile (first) all the way up to desktop
    @media screen and (min-width: 480px){
        /** ...styles for 480px and up go here **/
    }
  1. Reference the respond.min.js script (1kb min/gzipped) after all of your CSS (the earlier it runs, the greater chance IE users will not see a flash of un-media'd content)

  2. Crack open Internet Explorer and pump fists in delight

CDN/X-Domain Setup

Respond.js works by requesting a pristine copy of your CSS via AJAX, so if you host your stylesheets on a CDN (or a subdomain), you'll need to set up a local proxy to request the CSS for old IE browsers. Prior versions recommended a deprecated x-domain approach, but a local proxy is preferable (for performance and security reasons) to attempting to work around the cross-domain limitations.

Support & Caveats

Some notes to keep in mind:

How's it work?

Basically, the script loops through the CSS referenced in the page and runs a regular expression or two on their contents to find media queries and their associated blocks of CSS. In Internet Explorer, the content of the stylesheet is impossible to retrieve in its pre-parsed state (which in IE 8-, means its media queries are removed from the text), so Respond.js re-requests the CSS files using Ajax and parses the text response from there. Be sure to configure your CSS files' caching properly so that this re-request doesn't actually go to the server, hitting your browser cache instead.

From there, each media query block is appended to the head in order via style elements, and those style elements are enabled and disabled (read: appended and removed from the DOM) depending on how their min/max width compares with the browser width. The media attribute on the style elements will match that of the query in the CSS, so it could be "screen", "projector", or whatever you want. Any relative paths contained in the CSS will be prefixed by their stylesheet's href, so image paths will direct to their proper destination

API Options?

Sure, a couple:

Alternatives to this script

This isn't the only CSS3 Media Query polyfill script out there; but it damn well may be the fastest.

If you're looking for more robust CSS3 Media Query support, you might check out https://code.google.com/p/css3-mediaqueries-js/. In testing, I've found that script to be noticeably slow when rendering complex responsive designs (both in filesize and performance), but it really does support a lot more media query features than this script. Big hat tip to the authors! :)

Respond (scottjehl/Respond)

Searching Database…

11.2K ·GitHub
archived
Что это такое?Быстрая и лёгкая JavaScript-полифилл-библиотека, которая добавляет в браузеры без поддержки медиазапросов CSS3 с min/max-width — в первую очередь Internet Explorer 8 и старше — поддержку таких запросов, чтобы адаптивная вёрстка работала и там.
Это CSS-фреймворк или просто скрипт, который я подключаю к странице?Никакой не фреймворк — один небольшой скрипт (3 КБ в минифицированном виде, 1 КБ в сжатом gzipped) без зависимостей, разве что в комплекте идёт полифилл matchMedia. Браузеры, которые уже поддерживают медиазапросы, отсеиваются быстрой проверкой, так что скрипт фактически работает только там, где он нужен.
С чего начать, чтобы использовать его на своём сайте?Пишите медиазапросы с min/max-width в своём CSS как обычно, а затем подключайте respond.min.js после всего вашего CSS — чем раньше скрипт отработает, тем меньше шансов, что пользователи IE увидят вспышку неоформленного контента.
Он поддерживает любые медиазапросы?Поддержка намеренно узкая: обрабатываются только запросы min-width и max-width (для любых типов носителей). Вложенные медиазапросы не поддерживаются, а CSS, подключённый через @import или находящийся внутри элементов style, игнорируется.
Где он работает — в браузере, или мне нужно что-то на сервере?Полностью на стороне клиента, но он повторно запрашивает текст вашего CSS через Ajax, поэтому страницы должны отдаваться по HTTP (при file:// не работает), а стили с CDN или поддомена нужно проксировать локально, чтобы отдавать их старому IE.
Проект ещё поддерживается — стоит ли использовать его сегодня?Нет. Репозиторий заархивирован, а целевые браузеры (IE 6-8) давно устарели — все современные браузеры обрабатывают медиазапросы нативно. Относитесь к нему как к legacy-заплатке для очень старых кодовых баз, а не как к зависимости для новых проектов.
Почему ему нужно заново скачивать мой CSS?IE 8 и старше выбрасывают медиазапросы при разборе таблиц стилей, поэтому Respond.js загружает исходный CSS через Ajax, находит блоки с запросами с помощью регулярных выражений и вставляет их как элементы style, которые включает и отключает по мере изменения ширины окна.
Какие самые неприятные подводные камни стоит учитывать?Держите правила @font-face вне медиазапросов, иначе IE 7/8 зависнет при загрузке, не превышайте 32 таблицы стилей, иначе IE выдаст ошибку, избегайте кодировки UTF-8 с BOM, и имейте в виду, что комментарии с отладочной информацией Sass/SCSS ломают парсер.
Он предоставляет какой-нибудь JavaScript API?Небольшой: respond.update() заново запускает парсер после того, как вы добавили таблицу стилей, respond.mediaQueriesSupported сообщает, обрабатывает ли браузер запросы нативно, а respond.getEmValue() возвращает значение одного em в пикселях.
Creator
scottjehl
Size
0.3 MB
Stars
11.2K
Age
15y
Commits · 90 Days