Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Dupal 7 Resource friendly window resize listener
// Make sure we have the Drupal object, or make one
var Drupal = Drupal || { 'settings': {}, 'behaviors': {}, 'locale': {} };
/**
* Resource conscious resize handler
*
* This was grabbed from: https://developer.mozilla.org/en-US/docs/Web/Events/resize
* @param {function} Function that should be run on resize
*
* Example:
* Drupal.optimizedResize.add(function() {
* console.log('Window was resized!');
* });
*/
Drupal.optimizedResize = (function() {
var callbacks = [],
running = false;
// Fired on resize event.
function resize() {
if (!running) {
running = true;
if (window.requestAnimationFrame) {
window.requestAnimationFrame(runCallbacks);
} else {
setTimeout(runCallbacks, 66);
}
}
}
// Run the actual callbacks.
function runCallbacks() {
callbacks.forEach(function(callback) {
callback();
});
running = false;
}
// Adds callback to loop.
function addCallback(callback) {
if (callback) {
callbacks.push(callback);
}
}
return {
// Public method to add additional callback.
add: function(callback) {
if (!callbacks.length) {
window.addEventListener('resize', resize);
}
addCallback(callback);
}
}
}());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.