Why does window.onresize gets called when a page is loading?
Asked Answered
P

4

9

A JavaScript question.

Does anyone know why that in some browsers window.onresize gets called when the page is loading?

Can this be avoided?

I found the problem in IE, Firefox 27 for Android mobile(Tested on Samsung Galaxy S3), Google Nexus 7(Tested on Browserstack) and Windows Phone 8(Internet Explorer).

My testpage look like this:

    <!doctype html>

<html>

<head>

<meta charset="utf-8">

<title>Test</title>

    <script type="text/javascript">

    window.onresize = resize;

    function resize(){

    alert("resize event detected!");
    }

    </script>

</head>

<body>
</body>

</html>

Solution:

var windowWidth = $(window).width();

window.onresize = resize;

function resize(){

   if($(window).width()!=windowWidth){

      alert("Bingo");
          windowWidth = $(window).width();
   }

}
Polyhydric answered 17/2, 2014 at 15:18 Comment(4)
Can you provide a specific browser in which this occurs?Ailee
Could it be that the slow loading of images force a resize? E.g. your page renders initially with a lower size, than the image is done fetching, a redraw happens and it need to resize the page to make space for the image? (Solution: Give absolute width/height in the img tag)Distributary
Do you get this behaviour on the simplest of HTML documents (i.e. just an empty page with the above javascript and no styles or images at all)?Ailee
@LasseBrosolatJensen thanks - it might be something to do with the visual viewport on mobile browsers. Please see the edit in my answer.Ailee
A
3

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 H1s 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.

Ailee answered 17/2, 2014 at 15:27 Comment(7)
this doesn't answer the main question: why does this happen. you're only explainung how to avoid the consequences of this behaviour.Antinucleon
@Ailee Thank you for responding. I do not think your script will work in browsers that do not call window.onresize when pages load.Polyhydric
@LasseBrosolatJensen Yes you are right. My code for that assumes there is always a single onresize event fired on page load for all browsers. Without knowing which browsers do/do not do this, I think it's impossible to do effectively.Ailee
@Ailee Thank you for looking into this. I would like to mention that in Window 8.1 IE 11: If I stand in the address bar and press "Enter" the window.onresize also gets called. I have tested this on my own computer and also at Browserstack :-) ! But thank you.Polyhydric
@LasseBrosolatJensen no problem - very interesting re: IE11 on 8.1!Ailee
@LasseBrosolatJensen glad you found a solution - very nice.Ailee
Firefox is also, strangely, giving 2 onresize calls when you switch tabs, then come back. Very strange issue!Uroscopy
A
1

I had the same issue on Chrome 36 for Android. A resize event was triggered at some point on first page load when I was not expecting this to happen (it causes some minor visual glitch at page rendering). After investigating I tried to remove the part of my JavaScript that was dynamically appending the meta name="viewport" tag information after the document.ready event has fired (I used jQuery) and no more hazardous firing of the resize event.

One explanation could be that appending the viewport information after the page has already begun rendering will cause the resize event to trigger (which does make sense).

Of course this will only happen for browsers which do take the meta name="viewport" tag information into account i.e. mobile browsers mainly (I have not tested IE11 on 8.1 but given it is an hybrid OS it could be taking into account meta name="viewport" tag information).

Auroraauroral answered 2/8, 2014 at 11:13 Comment(0)
U
1

I had the issue that sometimes multiple resize events where fired after loading the page. To ensure only real resize events are considered, I used a timer to ignore the event for the first 500ms after page load. This way, it will work in all browsers, regardless whether they fire one or multiple resize events after loading.

var realResize = false;

setTimeout(function() {
  realResize = true;
}, 500);

window.onresize = function() {
  if (realResize) {
    // do something
  }
};
Unaesthetic answered 21/10, 2015 at 23:59 Comment(0)
K
0

This is quite an old post but it helped me resolve a similar problem

Indeed some mobile in 2023 raise a resize event during the load and more importantly in // of the processing (Brave and Safari, but not Chrome or Firefox !!)

This was causing a problem when trying to identify the component to display to be responsive to the window width.

After investigating I resolved the problem by only registering the event handle on resize after the page has fully loaded

Code example with vue js, placing this code in the router

window.addEventListener("load", () => {
  window.addEventListener("resize", () => {
    // get the current route
    const route = router.currentRoute.value;
    console.log("router resize triggered on route", route.fullPath);
    // force the router to reevaluate the path according to size
    router.push({path: route.path, query: route.query, hash: route.hash, force: true});
  });
});

function isMobile(): boolean {
  return window.innerWidth < 768;
}

// The router guard to force any route to be 
//   --> /mobile/xxx or ---> /desktop/xxx
router.beforeEach((to, from, next) => {
  // here test if the window size is small enough to be considered as a mobile
  let path = to.fullPath;
  path = path.replace(/\/(desktop|mobile)\//, "/");

  if (isMobile() && !to.fullPath.startsWith("/mobile/")) {
    return next({
      path: `/mobile${path}`,
      // params: to.params,
      query: to.query,
      hash: to.hash,
    });
  }
  if (!isMobile() && !to.fullPath.startsWith("/desktop/")) {
    return next({
      path: `/desktop${path}`,
      // params: to.params,
      query: to.query,
      hash: to.hash,
    });
  }
  return next();
});

Kunin answered 18/10, 2023 at 22:25 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.