Skip to content

Commit 47d6e6e

Browse files
committed
Added comments, fixed typo, changed appendChild to insertBefore, minor clean up and creation of tests.
1 parent 28929cc commit 47d6e6e

1 file changed

Lines changed: 18 additions & 23 deletions

File tree

matchMedia.js

Lines changed: 18 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -3,43 +3,38 @@
33
window.matchMedia || (window.matchMedia = function() {
44
"use strict";
55

6-
var styleMedia = (window.styleMedia || window.media);
6+
// For browsers that support matchMedium api such as IE 9 and webkit
7+
var styleMedia = (window.styleMedia || window.media);
78

8-
// For those that doen't support matchMedium
9+
// For those that don't support matchMedium
910
if (!styleMedia) {
1011
var style = document.createElement('style'),
11-
info = null,
12-
setStyle = function(text) {
13-
if (style.styleSheet) {
14-
style.styleSheet.cssText = text;
15-
} else {
16-
style.textContent = text;
17-
}
18-
};
12+
script = document.getElementsByTagName('script')[0],
13+
info = null;
1914

2015
style.type = 'text/css';
2116
style.id = 'matchmediajs-test';
2217

23-
document.getElementsByTagName('head')[0].appendChild(style);
18+
script.parentNode.insertBefore(style, script);
19+
20+
// 'style.currentStyle' is used by IE <= 8 and 'window.getComputedStyle' for all other browsers
2421
info = ('getComputedStyle' in window) && window.getComputedStyle(style) || style.currentStyle;
2522

2623
styleMedia = {
2724
matchMedium: function(media) {
28-
var text = '@media ' + media + '{ #matchmediajs-test { width: 1px; } }',
29-
match;
30-
31-
// Add css text
32-
setStyle(text);
25+
var text = '@media ' + media + '{ #matchmediajs-test { width: 1px; } }';
3326

34-
match = info.width === '1px';
35-
36-
// remove css text
37-
setStyle('');
27+
// 'style.styleSheet' is used by IE <= 8 and 'style.textContent' for all other browsers
28+
if (style.styleSheet) {
29+
style.styleSheet.cssText = text;
30+
} else {
31+
style.textContent = text;
32+
}
3833

39-
return match;
34+
// Test if media query is true or false
35+
return info.width === '1px';
4036
}
4137
};
42-
4338
}
4439

4540
return function(media) {
@@ -48,4 +43,4 @@ window.matchMedia || (window.matchMedia = function() {
4843
media: media || 'all'
4944
};
5045
};
51-
}());
46+
}());

0 commit comments

Comments
 (0)