matchMedia (v7)

Revision 7 of this benchmark created on


Description

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 HTML

<script src="https://raw.github.com/weblinc/media-match/master/media.js"></script>

Setup

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 = "&shy;<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 ));

Teardown


    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);
    }
    
  

Test runner

Ready to run.

Testing in
TestOps/sec
native matchMedia
window.matchMedia('screen and (min-width: 600px) and (min-height: 400px), screen and (min-height: 400px)');
ready
Media.match
Media.match('screen and (min-width: 600px) and (min-height: 400px), screen and (min-height: 400px)');
ready
polyfill paulirish/scottjehl/matchMedia.js
window.matchMediaPolyfill('screen and (min-width: 600px) and (min-height: 400px), screen and (min-height: 400px)');
ready

Revisions

You can edit these tests or add more tests to this page by appending /edit to the URL.