0
votes

I've attached the onresize listener to the body tag just fine but when I change my code to access the window.innerWidth and window.innerHeight my resize event only works one time.

<script type="text/javascript">
    function showMsg()
    {
        document.write((window.innerWidth / window.innerHeight) * 100 + "%");
    }
</script>
<body onresize="showMsg()">
1

1 Answers

1
votes

Makes sense, have you tried checking the source of your page after the function has returned? there's no more body tag is there - with it goes your event listener (or could still be in memory, dangling uselessly).
Try attaching it to window.

window.onresize = function()
{
    document.write((this.innerWidth/this.innerHeight)*100+'%');
};

Now in older version of a formerly very popular browser this (attaching event listeners to the window object) causes memory leaks. The window object is never really destroyed more info here if you need it.

how to solve the mem issue?

(function(win)
{
    win.onresize = function()
    {
        document.write((this.innerWidth/this.innerHeight)*100+'%');
    };
    if (win.attachEvent)
    {
        win.attachEvent('onbeforeunload',(function(self)
        {
            return function freeMem()
            {
                self.onresize = null;
                self.detachEvent('onbeforeunload',freeMem);
            };
        })(win));
        return;
    }
    win.addEventListener('beforeunload',(functio(self)
    {
        return function freeMem()
        {
            self.onresize = null;
            self.removeEventListener('beforeUnload',freeMem,false);
        };
    })(win),false);
})(this);//this points to current window

I know, looks awful, but I've tested this and it does the trick - Thanks for that IE. Strictly speaking the closures passing win to self could be omitted, but I keep it in there to be absolutely sure, as soon as the onbeforeunload event fires, and the handler returns all functions and refernces go out of scope, so the GC's have no reason not to free the memory.
It's overkill in most situations, but just in case someone cares, I decided to post it here... :-P