Last active
January 15, 2016 02:29
-
-
Save mjlescano/c4a70f4cd4460cd39c11 to your computer and use it in GitHub Desktop.
window.onresize handler with a debounced calling to avoid unnecessary re-paints
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
/** | |
* onResize.js | |
* | |
* `window.onresize` handler with a debounced calling to avoid unnecessary re-paints. | |
* | |
* e.g.: | |
* onResize.add(function(){ | |
* console.log('Executed on window resize! But debounced.') | |
* }) | |
* | |
* Matías Lescano | @mjlescano | |
* Licensed under the MIT license | |
*/ | |
;if( !window.onResize ) (function(w){ | |
function debounce (func, wait, immediate) { | |
var timeout | |
return function () { | |
var context = this | |
var args = arguments | |
var later = function () { | |
timeout = null | |
if (!immediate) func.apply(context, args) | |
} | |
var callNow = immediate && !timeout | |
clearTimeout(timeout) | |
timeout = setTimeout(later, wait) | |
if (callNow) func.apply(context, args) | |
} | |
} | |
var cbs = [] | |
var execute = debounce(function _execute() { | |
for (var i = 0, l = cbs.length; i < l; i++) cbs[i]() | |
}, 300) | |
if (w.addEventListener) { | |
w.addEventListener('resize', execute) | |
} else { | |
w.attachEvent('onresize', execute) | |
} | |
w.onResize = { | |
add: function(cb){ | |
cbs.push(cb) | |
return w.onResize | |
}, | |
remove: function(cb){ | |
for (var i = 0, l = cbs.length; i < l; i++) { | |
if (cb === cbs[i]) { | |
cbs.splice(i,1) | |
break | |
} | |
} | |
return w.onResize | |
} | |
} | |
})(window); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment