Sebastiaan Ordelman
Sebastiaan Ordelman

Reputation: 942

HTML viewport tag sometimes ignored in mobile Chrome on first visit

For my adaptive website, I use the viewport meta tag to force the device to show the page in its "preferred" screen resolution (not actual device resolution, but the "smallest" resolution with initial scale 1.0).

Viewport meta tag:

<meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0">

This seems to work well on all devices, but, on mobile Chrome and sometimes on IOS devices, first/uncached visit does not detect the device's "preferred" resolution right away, but communicates the actual screen resolution.

Setup to reproduce the error (in head section of the page):

<meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0">
<script type="text/javascript">
    alert(window.innerWidth);
</script>

First/uncached visit will show "980" for my Nexus 5, second visit/refresh will show the desired "360".

Does anybody know a way to force the window to use initial scale, without javascript timeout or window onload workarounds?


Edited: Checking window.innerWidth after window.onload returns the desired "preferred" width. That is my workaround for now...

Upvotes: 3

Views: 1239

Answers (1)

Sebastiaan Ordelman
Sebastiaan Ordelman

Reputation: 942

I found a solution: window.innerWidth is somehow delayed and returns the value of the not-viewport-resized document width in an early stage of the page load. document.documentElement.clientWidth seems to have no problems when calculating window width in early page load stage.

<meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0">
<script type="text/javascript">
    // So use this to calculate device width rules before window.onload
    alert(document.documentElement.clientWidth);
</script>

Note: You are able to use window.innerWidth later on, e.g. after window.onload.

Upvotes: 1

Related Questions