17

Aug 2014

Responsive website with Matchmedia

Media queries is a great tool, but we often got a problem on loading time and optimization. Often time our website load all the things – even when they don’t apply.

Scott Jehl, Paul Irish, Nicholas Zaka attempts to optimise the loading of CSS based on viewport size and other factors. By using matchMedia() polyfill, we can now test whether a CSS media type or media query applies. Check out Paul Rhayes how to’s, experiment and Christian Hielmann Demo.

Your CSS

.mq {
  -webkit-transition: width 0.001ms;
  -moz-transition: width 0.001ms;
  -o-transition: width 0.001ms;
  transition: width 0.001ms;
  width: 0;
}

Javascript Event Listener

mql = (function(doc, undefined){

  var bool,
      docElem  = doc.documentElement,
      refNode  = docElem.firstElementChild || docElem.firstChild,
      idCounter = 0;

  return function(q, cb) {

    var id = 'mql-' + idCounter++,
      callback = function() {
        cb({ matches: (div.offsetWidth == 42), media: q });
      },
      div = doc.createElement('div');

    div.className = 'mq';
    div.style.cssText = "position:absolute;top:-100em";
    div.id = id;
    div.innerHTML = ' #'+id+' { width: 42px; }';

    div.addEventListener('webkitTransitionEnd', callback, false);
    div.addEventListener('transitionend', callback, false); //Firefox
    div.addEventListener('oTransitionEnd', callback, false); //Opera

    docElem.insertBefore(div, refNode);
    //don’t delete the div, we need to listen to events
    return {
      matches: div.offsetWidth == 42,
      media: q
    };
  };

})(document);

Javascript on the page

$(function() {
  var $dynamic = $('.dynamic');
  mql('all and (max-width: 700px)', change);
  mql('all and (max-width: 500px)', change);
  mql('all and (min-width: 1200px)', change);

  function change(mql) {
    console.log(mql);
    $dynamic.prepend('

' + mql.media + ' — ' + mql.matches + '

'); } });