Skip to main content Skip to secondary navigation Accessibility Feedback

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.

Psst... I'm writing a book on ditching jQuery for vanilla JS. Pre-order it today and save 50%.

Throttling Your JavaScript #

JS resize throttling is a two-part approach:

  1. You create a function that does whatever you need to have happen on resize.
  2. 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.

If you liked this article, you might also like Ditching jQuery, my new beginner's guide to vanilla JavaScript. Pre-order it today and save 50%.
  • More articles on...
  • Code

Have any questions or comments about this post? Email me at chris@gomakethings.com or contact me on Twitter at @ChrisFerdinandi.

Get Weekly Digests