Last active
August 29, 2015 14:19
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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