Maybe something like this? Please see comments in code.
function testSupportMsViewport() {
let result = false;
let s = document.createElement('style');
let test = document.createElement('div');
// create style rule to make viewport 200px in width
// if @-ms-viewport is interpreted
s.innerHTML = '@-ms-viewport { width: 200px; }';
// hide any overflow hence we do not need to take scrollbars into account
s.innerHTML += '* { overflow-y: hidden; }';
// use fixed position, block box sizing and no paddings/margins/borders
// together with a width of 1% (which is 2px when the viewport is 200px)
s.innerHTML += '.foo { position: fixed; display: block; padding: 0; border: 0; margin: 0; width: 1%; }';
test.classList += 'foo';
// append the style element and the test div to the html element
// applying the test styles to the div
// note that we're not appending it to body since there may be
// styles applied which could disturb calculations
document.documentElement.appendChild(s);
document.documentElement.appendChild(test);
// check width of test div. If the browser interprets the rule,
// it should be 2 (2px)
// obviously, this yields a false-positive when the viewport really is just 200px in width. Think about using some other value or add additional checks
if (parseFloat(window.getComputedStyle(test).width) === 2) {
result = true;
}
// Remove elements since they're not needed anymore
document.documentElement.removeChild(s);
document.documentElement.removeChild(test);
return result;
}
I was not able to test that snippet in Edge since I'm not using Windows. However, the function returns true
if the viewport is 200px in width and false otherwise.
(If you're targeting ES5, you may replace the let
by var
)