Forums

The forums ran from 2008-2020 and are now closed and viewable here as an archive.

Home Forums JavaScript Getting Media Queries working on old IE Re: Getting Media Queries working on old IE

#88855
rjc
Member

Thanks Mottie! Using jquery really cleans up the code compared to plain javascript, it’s much easier to read and understand.

Maybe a problem with the above is that it browsers that natively understand media queries are marginally slower as they now have to wait for jquery script to download and execute before styles are activated for the site. As you say i guess the key to using this is to have a base style that is close to the width dependent ones so the change is not too abrupt.

Anyway I borrowed the regular expression to parse the min and max values from the respond.js script and reworked the script i posted from yesterday. Using the same stylesheet links before with this code now seems to work(am thinking perhaps is some kind of race condition say a page loading and onresize script running concurrently or something):


/*
* Workaround lack of media queries on older versions of IE
*/

var maxwidth_re = /(max-width:[s]*([s]*[0-9]+)px[s]*)/;
var minwidth_re = /(min-width:[s]*([s]*[0-9]+)px[s]*)/;

var saved_stylesheet_media = [];
var resize_timeout_id = null;

function ieMediaQuery() {
//enable layout stylesheet dependent on width
var width = document.documentElement.offsetWidth;

for (var i = 0; i < document.styleSheets.length; i++) {
var s = document.styleSheets;
if (s.title == "layout width") {
if (saved_stylesheet_media
== undefined) {
saved_stylesheet_media
= s.media;
}
var ssminwidth = (minwidth_re.test(saved_stylesheet_media
)) ? RegExp.$1 : 0;
var ssmaxwidth = (maxwidth_re.test(saved_stylesheet_media
)) ? RegExp.$1 : Number.MAX_VALUE;
s.disabled = (width < ssminwidth || width > ssmaxwidth);
if (s.disabled == false) {
s.media = "screen";
}
}
}
}

document.write("");
var script = document.getElementById("__ie_onload");
script.onreadystatechange = function() {
if (/^(complete|loaded)$/.test(script.readyState)) {
script.onreadystatechange = null;
ieMediaQuery();
window.attachEvent("onresize", function() {
window.clearTimeout(resize_timeout_id);
resize_timeout_id = window.setTimeout('ieMediaQuery();', 10);
});
}
};

[Edit: Fixed bug in above code, which would lose the original media values]

Edit 2:
Just for people looking at this future, above script works for me now, to use
1) Copy above into a script file say iemediaquery.js
2) Create an empty file empty.js as a dummy target(other solutions would not work for me with ssl, got mixed content warnings)
3) Setup your stylesheets as in first post with ‘title’ and ‘media’ attributes and then add conditional to load for IE 6-8 afterwards:



4) Media queries should work for old IE!