On a hint from Vasilis I did some quick research into dynamically changing the meta viewport tag. Turns out that this works in nearly all browsers that support it in the first place, with the exception of Firefox. This entry gives the details and explains why you should care. See also the inevitable compatibility table.
This is a meta viewport tag:
<meta name="viewport" content="width = 380" id="testViewport">
It sets the layout viewport width to 380 pixels. This works in most modern browsers; Nokia WebKit being the prime exception.
Now usually setting a width as above is enough for your pages, but there are situations in which you want more flexibility in your width-setting. For instance, you might want to give the layout viewport a width of 380px unless you’re on a widescreen (read tablet) device, in which case you might want to double it to 740. Or whatever.
In any case, this works in all browsers that support meta viewport except for Firefox:
<meta id="testViewport" name="viewport" content="width = 380"> <script> if (screen.width > 740) { var mvp = document.getElementById('testViewport'); mvp.setAttribute('content','width=740'); } </script>
Note that the script comes directly after the meta viewport tag itself, and does not wait for anything: it’s executed automatically and changes the meta viewport tag directly. The advantage of this is that the browser is immediately notified of the change and can use the 740px-wide layout viewport during the remainder of the downloading, parsing and rendering process for calculating percentual widths in the CSS, media queries, and everything else that depends on the layout viewport width.
It’s also possible to force a change much later, after the page has been downloaded and rendered:
<meta id="testViewport" name="viewport" content="width = 380"> <script> window.onload = function () { if (screen.width > 740) { var mvp = document.getElementById('testViewport'); mvp.setAttribute('content','width=740'); } } </script>
Now the browser has to change the already-rendered page, so it wouldn’t surprise me a bit if this use is computationally expensive. That may be the reason that this variation isn’t as widely supported as the previous one: only iPhone, Android, and Palm change the layout viewport here. Opera, Dolfin for bada, BlackBerry, Firefox, IE and Obigo do not.
I tend to think that the first variant is the best one; both for its browser support and because it doesn’t require the page and its assets to be interpreted and rendered twice.
This is the blog of Peter-Paul Koch, web developer, consultant, and trainer.
You can also follow
him on Twitter or Mastodon.
Atom
RSS
If you like this blog, why not donate a little bit of money to help me pay my bills?
Categories: