As far as I can tell, window.onresize not called when the default page loads on desktop browsers
I wrote a simple html page as follows (many H1 so that the page has some content):
<!DOCTYPE html> <html> <head> <script> var i = 0; window.onresize = function() { i++; } window.setTimeout(function() { alert("resize called " + i + " times"); }, 2000); </script> </head> <body> <h1>test</h1> <h1>test</h1> <h1>test</h1> <h1>test</h1> <h1>test</h1> <h1>test</h1> <h1>test</h1> <h1>test</h1> <h1>test</h1> <h1>test</h1> <h1>test</h1> <h1>test</h1> <h1>test</h1> <h1>test</h1> <h1>test</h1> <h1>test</h1> <h1>test</h1> <h1>test</h1> <h1>test</h1> <h1>test</h1> </body> </html>
The warning shows 0 in the following browsers:
- Chrome 32
- Firefox 26
- Opera 12
- IE11
- IE8
- Safari 5.1.7
Theory of viewing mobile browsers
I see that your problems seem to be on mobile devices. onresize may work when the page loads due to the resizing of the "visual viewing" after the mobile browser has downloaded the content and figured out how to scale the page to fit the screen.
See here for an explanation of mobile viewports:
http://www.quirksmode.org/mobile/viewports2.html
And look here for a table of how several mobile browsers handle the onresize event for the visual viewport:
http://www.quirksmode.org/dom/events/resize_mobile.html
If so, I think it can be very difficult for you to deal with it.
Ignoring the first call to onresize
To avoid starting the event handler for onresize for the onresize , you can simply set the flag as follows:
var initial = true; $(window).on('resize',function(){ if(!initial) {
However, as you say in the comments, this will not work if onresize works as expected (and does not work when the page loads). He assumes that the first run will be on page loading.
theyetiman
source share