Reputation: 115
I created 4 different .css files for handling different resolutions.
Here is the jquery code I'm using to load the files based on screen width.
<link id="size-stylesheet" rel="stylesheet" type="text/css" href="public/_css/normal.css" />
<script language="javascript" type="text/javascript">
function adjustStyle(width)
{
width = parseInt(width);
if(width >= 1920)
{
$("#size-stylesheet").attr("href", "public/_css/bigger.css");
}
else if (width >= 1600)
{
$("#size-stylesheet").attr("href", "public/_css/big.css");
}
else if (width >= 1366)
{
$("#size-stylesheet").attr("href", "public/_css/normal.css");
}
else
{
$("#size-stylesheet").attr("href", "public/_css/small.css");
}
}
$(function()
{
adjustStyle($(this).width());
$(window).resize(function()
{
adjustStyle($(this).width());
});
});
</script>
When I test the page on chrome, everytime I resize the window it flickers like crazy. Oddly it works perfectly fine on IE8 and firefox.
Here is the working example of the page;
I have a feeling that everytime I resize the window, it keeps loading the css files over and over again.
It also takes some time to load the css files when the window is resized, so is it possible to load them beforehand?
Upvotes: 0
Views: 4201
Reputation: 17930
Try adding another condition to each if:
if(width >= 1920 && !$("#size-stylesheet").attr("href") === "public/_css/bigger.css")
{
$("#size-stylesheet").attr("href", "public/_css/bigger.css");
}
else if (width >= 1600 && !$("#size-stylesheet").attr("href") === "public/_css/big.css")
{
$("#size-stylesheet").attr("href", "public/_css/big.css");
}
...
That way you only replace the css once and not every time a resize happens
Upvotes: 0
Reputation: 6610
You're getting spotty behaviour because the browser is not supposed to do such heavy computations during window.onresize
. This event can fire hundreds of times per second, and you definitely do not want a queue of 100 AJAX requests being requested, served, downloaded and parsed all the time.
I highly recommend using media queries, and since you're already open to using Javascript, you may be interested in using a CSS3 media query polyfill for IE6-8.
It's more future-proof, and when you stop needing to support these legacy browsers, all you have to do is stop using the polyfill, instead of converting everything to 'proper' CSS the second time around.
Upvotes: 3