0
# Core Media Query Polyfill
1
2
The core respond.js polyfill enables CSS3 media queries in browsers that don't support them natively, particularly Internet Explorer 6-8. It works by parsing CSS files via AJAX, extracting media queries, and dynamically applying matching rules.
3
4
## Capabilities
5
6
### Global Respond Object
7
8
The main respond.js interface exposed on the window object.
9
10
```javascript { .api }
11
/**
12
* Main respond.js API object available globally
13
*/
14
interface Respond {
15
/**
16
* Re-parse all stylesheets and update media query application
17
* Useful when stylesheets are added dynamically to the page
18
*/
19
update(): void;
20
21
/**
22
* Get the pixel value of 1em for media query calculations
23
* @returns Current pixel value of 1em
24
*/
25
getEmValue(): number;
26
27
/**
28
* Flag indicating if browser natively supports media queries
29
* Set to true for browsers with native support (causes early exit)
30
*/
31
mediaQueriesSupported: boolean;
32
33
/**
34
* Internal AJAX function (exposed for testing)
35
* @param url - URL to fetch
36
* @param callback - Function called with response text
37
*/
38
ajax(url: string, callback: (responseText: string) => void): void;
39
40
/**
41
* Internal request queue (exposed for testing)
42
*/
43
queue: RequestItem[];
44
45
/**
46
* Regular expressions used for CSS parsing
47
*/
48
regex: RespondRegex;
49
}
50
51
/**
52
* Internal processing functions (exposed for testing)
53
*/
54
interface RespondInternals {
55
/**
56
* Parse CSS text and extract media query rules
57
* @param styles - CSS text content
58
* @param href - Stylesheet URL for relative path resolution
59
* @param media - Media attribute from link element
60
*/
61
translate(styles: string, href: string, media: string): void;
62
63
/**
64
* Apply media query rules based on current viewport
65
* @param fromResize - Whether called from resize event
66
*/
67
applyMedia(fromResize?: boolean): void;
68
69
/**
70
* Process request queue for CSS files
71
* Recursively processes queued AJAX requests
72
*/
73
makeRequests(): void;
74
75
/**
76
* Scan and parse all stylesheets in the document
77
* Main entry point for CSS processing
78
*/
79
ripCSS(): void;
80
}
81
82
declare global {
83
interface Window {
84
respond: Respond;
85
}
86
}
87
```
88
89
### Update Method
90
91
Re-parses all stylesheets and updates media query application. Essential for single-page applications or when CSS is loaded dynamically.
92
93
```javascript { .api }
94
/**
95
* Re-parse all stylesheets and update media query application
96
* Triggers a complete re-scan of all link elements and CSS parsing
97
*/
98
window.respond.update(): void;
99
```
100
101
**Usage Example:**
102
103
```javascript
104
// After dynamically adding a stylesheet
105
var link = document.createElement('link');
106
link.rel = 'stylesheet';
107
link.href = 'responsive.css';
108
document.head.appendChild(link);
109
110
// Update respond.js to process the new stylesheet
111
window.respond.update();
112
```
113
114
### Em Value Calculation
115
116
Returns the current pixel value of 1em for accurate media query calculations.
117
118
```javascript { .api }
119
/**
120
* Get the pixel value of 1em for media query calculations
121
* Creates a temporary element to measure current em value
122
* @returns Current pixel value of 1em
123
*/
124
window.respond.getEmValue(): number;
125
```
126
127
**Usage Example:**
128
129
```javascript
130
// Get current em value in pixels
131
var emInPixels = window.respond.getEmValue();
132
console.log('1em = ' + emInPixels + 'px');
133
134
// Useful for JavaScript calculations that need to match CSS media queries
135
if (window.innerWidth >= (30 * emInPixels)) { // 30em breakpoint
136
// Apply JavaScript behavior for larger screens
137
}
138
```
139
140
### Media Query Support Detection
141
142
Flag indicating whether the browser natively supports CSS3 media queries.
143
144
```javascript { .api }
145
/**
146
* Flag indicating if browser natively supports media queries
147
* Set to true for browsers with native support, causing respond.js to exit early
148
*/
149
window.respond.mediaQueriesSupported: boolean;
150
```
151
152
**Usage Example:**
153
154
```javascript
155
if (window.respond.mediaQueriesSupported) {
156
console.log('Browser has native media query support');
157
} else {
158
console.log('Using respond.js polyfill');
159
}
160
161
// Conditional JavaScript behavior
162
if (!window.respond.mediaQueriesSupported) {
163
// Add extra fallbacks for IE8 and below
164
document.documentElement.className += ' no-mediaqueries';
165
}
166
```
167
168
## CSS Processing Rules
169
170
### Supported Media Query Features
171
172
Respond.js supports a focused subset of CSS3 media queries:
173
174
- **min-width** queries with px or em units
175
- **max-width** queries with px or em units
176
- **All media types** (screen, print, projection, etc.)
177
- **Media attributes** on link elements (when no internal queries exist)
178
179
### CSS Parsing Behavior
180
181
```javascript
182
// Supported patterns:
183
@media screen and (min-width: 480px) { /* styles */ }
184
@media print and (max-width: 600px) { /* styles */ }
185
@media (min-width: 30em) and (max-width: 60em) { /* styles */ }
186
187
// Link element media attributes:
188
<link rel="stylesheet" href="print.css" media="print" />
189
<link rel="stylesheet" href="mobile.css" media="screen and (max-width: 480px)" />
190
```
191
192
### Limitations
193
194
- **@import stylesheets**: Not parsed (must use `<link>` elements)
195
- **Inline `<style>` elements**: Not processed (CSS must be in external files)
196
- **@font-face in media queries**: Causes IE7/8 to hang (place outside queries)
197
- **Nested media queries**: Not supported
198
- **Complex media features**: Only min/max-width supported
199
- **File protocol**: May not work on file:// URLs due to security restrictions
200
- **Redirected CSS**: Fails silently if CSS returns non-200 status
201
- **UTF-8 BOM**: Breaks functionality in IE7/8
202
203
## Internal Architecture
204
205
### CSS Processing Pipeline
206
207
1. **Stylesheet Discovery**: Scans all `<link rel="stylesheet">` elements
208
2. **AJAX Retrieval**: Fetches CSS content via XMLHttpRequest
209
3. **Media Query Extraction**: Uses regex to find @media blocks
210
4. **Rule Parsing**: Extracts min/max-width values and media types
211
5. **Viewport Evaluation**: Compares rules against current window dimensions
212
6. **Style Injection**: Creates `<style>` elements for matching rules
213
7. **Resize Monitoring**: Listens for window resize with 30ms throttling
214
215
### Regular Expressions
216
217
```javascript { .api }
218
interface RespondRegex {
219
/** /@media[^\{]+\{([^\{\}]*\{[^\}\{]*\})+/gi - Matches @media blocks */
220
media: RegExp;
221
222
/** /@(?:\-(?:o|moz|webkit)\-)?keyframes[^\{]+\{(?:[^\{\}]*\{[^\}\{]*\})+[^\}]*\}/gi - Matches @keyframes */
223
keyframes: RegExp;
224
225
/** /(url\()['"]?([^\/\)'"][^:\)'"]+)['"]?(\))/g - Matches CSS url() functions */
226
urls: RegExp;
227
228
/** /@media *([^\{]+)\{([\S\s]+?)$/ - Extracts media conditions and content */
229
findStyles: RegExp;
230
231
/** /(only\s+)?([a-zA-Z]+)\s?/ - Matches media type with optional "only" */
232
only: RegExp;
233
234
/** /\([\s]*min\-width\s*:[\s]*([\s]*[0-9\.]+)(px|em)[\s]*\)/ - Matches min-width queries */
235
minw: RegExp;
236
237
/** /\([\s]*max\-width\s*:[\s]*([\s]*[0-9\.]+)(px|em)[\s]*\)/ - Matches max-width queries */
238
maxw: RegExp;
239
}
240
241
/** AJAX request queue item */
242
interface RequestItem {
243
/** URL of CSS file to fetch */
244
href: string;
245
/** Media attribute from link element */
246
media: string;
247
}
248
```