I'm having trouble with my web app using window.innerWidth and window.innerHeight before they seem to have stabilized. Things work fine on my desktop, but I run into this issue on multiple mobile devices (all running the current stable release of Chrome for Android). I've reduced things to what I think is the simplest way to reproduce the problem:
<!DOCTYPE html>
<html>
<head>
<!--meta name="viewport" content="initial-scale=1.0, maximum-scale=1.0, user-scalable=no" /-->
<!--meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" /-->
<script type="text/javascript">
function dimen() {
alert("" + window.innerWidth + "x" + window.innerHeight);
}
window.onload = dimen;
setTimeout(dimen, 1000);
</script>
</head>
<body>
</body>
</html>
On my Nexus 7, I get the following results:
Without viewport meta tag:
Initial load:
Refresh:
One-second pause:
With first viewport meta tag:
Initial load:
Refresh:
One-second pause:
With second viewport meta tag:
Initial load:
Refresh:
One-second pause:
Putting that all together, I see the following:
width=device-width does not seem to matter.window.onload is firing before the viewport meta tag is applied to the document. But differences are seen even without that tag, suggesting that either way, things aren't yet finalized when the code is first called.I had similar results (different dimensions, of course, but with the same overall pattern) on my Nexus 6, except that I once got "0x0" on initial load.
The Question
I'd like to know how to have my app wait to use window.innerWidth and window.innerHeight until they have finalized what they are going to be. I tried waiting for an animation frame, and somewhat surprisingly, that didn't work. Obviously waiting a second for my app to start is undesirable, as is decreasing the value of the timeout until I find something that "usually works". Am I doing something wrong? Is there a best practice for knowing when the values are safe to access?
Maybe you can use jQuery with
$( document ).ready(function() {
console.log('DOM ready');
//your functions here
});
(http://api.jquery.com/ready/)
If it is just a webapp you can use bootstrap too. (http://getbootstrap.com/) It's mobile-first tech. hope it helps a bit.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With