As far as I can tell, window.onresize
does not get called on page load by default on desktop browsers
I wrote a simple html page as follows (many H1
s to make the page have 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 alert shows 0 in the following browsers:
- Chrome 32
- Firefox 26
- Opera 12
- IE11
- IE8
- Safari 5.1.7
Mobile Browser Viewports Theory
I can see your problems seem to be on mobile devices. onresize
may fire on page load due to the "visual viewport" resizing after the mobile browser has loaded the content and figured out how to scale the page to your screen size.
See here for an explanation of mobile viewports:
http://www.quirksmode.org/mobile/viewports2.html
And see 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 this is the case then I think you might have a very tough time combating it.
Ignoring the first call to onresize
To avoid the first run of your event handler for onresize
you could simply set a flag like so:
var initial = true;
$(window).on('resize',function(){
if(!initial)
{
// do your stuff here
}else
{
// don't do your stuff here
}
initial = false;
});
However, as you say in the comments this will not work if onresize
is working as expected (and not running on page load). It assumes that the first run will be on page load.
img
tag) – Distributary