JavaScript Resize Performance
On a recent project, I used the jQuery .resize()
method to detect when a user resized their browser and run certain code.
There are performance concerns with doing so, though. Paul Irish explains…
If you’ve ever attached an event handler to the window’s resize event, you have probably noticed that while Firefox fires the event slow and sensibly, IE and Webkit go totally spastic.
Fortunately, there’s an easy fix: throttling.
Throttling Your JavaScript
JS resize throttling is a two-part approach:
- You create a function that does whatever you need to have happen on resize.
- Within the
.resize()
method, you run the function and set a timeout on it so it won't run again for a predefined amount of time.
Here’s what it looks like:
(function($) {
var resizeTimer; // Set resizeTimer to empty so it resets on page load
function resizeFunction() {
// Stuff that should happen on resize
};
// On resize, run the function and reset the timeout
// 250 is the delay in milliseconds. Change as you see fit.
$(window).resize(function() {
clearTimeout(resizeTimer);
resizeTimer = setTimeout(resizeFunction, 250);
});
})(jQuery);
You can adjust the delay based on how much of a lag you’re comfortable with. Even 100 milliseconds makes a big difference in performance. Check out this demo Ben Alman put together.
Running on Page Load
If you have stuff that you want to run on resize and page load, you can also call the function outside of .resize()
:
(function($) {
var resizeTimer; // Set resizeTimer to empty so it resets on page load
function resizeFunction() {
// Stuff that should happen on resize
};
// On resize, run the function and reset the timeout
// 250 is the delay in milliseconds. Change as you see fit.
$(window).resize(function() {
clearTimeout(resizeTimer);
resizeTimer = setTimeout(resizeFunction, 250);
});
resizeFunction();
})(jQuery);
Now, resizeFunction()
will run when the page loads, and again whenever the browser window is resized.