简体   繁体   中英

Why does IE8 hangs on jquery window.resize event?

I discovered a problem that seems to reproduce always when opening a piece of html and javascript in IE8.

<html>
    <body>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.0/jquery.min.js"></script>
    <script>
        $(document).ready(function(){
            $(window).resize(function() {
                console.log('Handler for .resize() called');
            });
        });
    </script>
    <div id="log">
    </div>
    </body>
</html>

Loading this file in IE8 and opening Developer Tools will show that the log message is printed continuously after one resize of the browser window.

Does anyone has an idea why? This is not happening in IE7 or IE9, nor in other browsers (or at least their latest versions).

UPDATE

One solution to prevent the continuos trigger of resize() is to add handler on document.body.onresize if the browser is IE8.

 var ieVersion = getInternetExplorerVersion();
    if (ieVersion == 8) {
        document.body.onresize = function () {
        };
    }
    else {
        $(window).resize(function () {
        });
    }

But this does not answer my question: is the continuous firing of resize() a bug in IE8?

If "show window contents while dragging" is switched on, you will be inundated with resize events. I guess you're testing IE8 on a separate Windows machine which has this effect enabled (Display Properties -> Appearance -> Effects...).

To counteract this, you can wrap & trap the resize events to tame them: http://paulirish.com/demo/resize

This article says Chrome, Safari & Opera suffer from this too.

I only see the issue you are describing if an element on the page is resized ( as described in this question ). Your example doesn't work for me, but I assume for you it is appending the console message in the log div that you have there, which means that it is resizing the div and triggering the window resize event.

The answer that Lee gave is correct, but the method in the link didn't work for me. Here's what I did:

var handleResize = function(){
   $(window).one("resize", function() {
      console.log('Handler for .resize() called');
      setTimeout("handleResize()",100);
   });
}
handleResize();

This way, the handler is unbound as soon as it fires, and is only re-bound after you've finished all your actions that might re-trigger a page resize. I threw in a setTimeout to provide additional throttling. Increase the value in case your scripts need more time.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM