matchMedia
JavaScript performance comparison
Info
window.matchMedia vs matchMedia.js polyfill & Media.match
This tests the performance of native window.matchMedia against matchMedia.js and Media.match.
matchMedia() polyfill
Test whether a CSS media type or media query applies. See http://github.com/paulirish/matchMedia.js
Media.match
Testing css media queries in Javascript. Not a polyfill and perhaps faster than native window.matchMedia. See http://github.com/weblinc/media-match
Preparation code
<script src="https://raw.github.com/weblinc/media-match/master/media.js"></script>
<script>
Benchmark.prototype.setup = function() {
window.matchMediaPolyfill = (function( doc, undefined ) {
"use strict";
var bool,
docElem = doc.documentElement,
refNode = docElem.firstElementChild || docElem.firstChild,
// fakeBody required for <FF4 when executed in <head>
fakeBody = doc.createElement( "body" ),
div = doc.createElement( "div" );
div.id = "mq-test-1";
div.style.cssText = "position:absolute;top:-100em";
fakeBody.style.background = "none";
fakeBody.appendChild(div);
return function(q){
div.innerHTML = "­<style media=\"" + q + "\"> #mq-test-1 { width: 42px; }</style>";
docElem.insertBefore( fakeBody, refNode );
bool = div.offsetWidth === 42;
docElem.removeChild( fakeBody );
return {
matches: bool,
media: q
};
};
}( document ));
};
Benchmark.prototype.teardown = function() {
if (window.removeEventListener) {
window.removeEventListener('resize', Media.watch);
window.removeEventListener('orientationchange', Media.watch);
} else if (window.detachEvent) {
window.detachEvent('onresize', Media.watch);
window.detachEvent('onorientationchange', Media.watch);
}
};
</script>
Preparation code output
Test runner
Warning! For accurate results, please disable Firebug before running the tests. (Why?)
Java applet disabled.
| Test | Ops/sec | |
|---|---|---|
native matchMedia |
|
pending… |
Media.match |
|
pending… |
polyfill paulirish/scottjehl/matchMedia.js |
|
pending… |
Compare results of other browsers
Revisions
You can edit these tests or add even more tests to this page by appending /edit to the URL. Here’s a list of current revisions for this page:
- Revision 4: published
- Revision 7: published
- Revision 11: published by David Knight
- Revision 12: published
- Revision 19: published
0 comments