Skip to content

Instantly share code, notes, and snippets.

@cuth
Last active August 29, 2015 14:19
Show Gist options
  • Save cuth/da11d46d5b1e7503c90e to your computer and use it in GitHub Desktop.
Save cuth/da11d46d5b1e7503c90e to your computer and use it in GitHub Desktop.
Run a function if a media query matches or once the media query eventually matches
var lazy = function (mediaQuery, load, unload) {
'use strict';
if (typeof mediaQuery !== 'string') return;
if (typeof load !== 'function') return;
var mql = matchMedia(mediaQuery);
var isLoaded = false;
if (mql.matches) {
load();
isLoaded = true;
if (typeof unload !== 'function') return;
}
mql.addListener(function () {
if (mql.matches && !isLoaded) {
load();
isLoaded = true;
} else if (typeof unload === 'function' && !mql.matches && isLoaded) {
unload();
isLoaded = false;
}
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment