Reputation:
I have a little JS-script that checks window-width on resize event and serves different full-screen background images specified on the html-side in data-attributes accordingly. Unfortunately, I cannot use a CSS-solution in this particular case.
The solution on its own works, but it does not incorporate images for retina displays. If I see this correctly, images for retina displays need twice the resolution to be displayed correctly. I have set the following breakpoints in the script: 1280 x 720px (retina: 2560 x 1440) , 1920 x 1080 px (retina: 3840 x 2160), larger than 2560 x 1440 px (retina: 5120 x 2880).
HTML:
<section id="page-title" class="page-title-lg img-cover header-lg" data-bg-xxl="test/2560.jpg" data-bg-xl="test/fullhd.jpg" data-bg-lg="test/hdready.jpg">
<div class="container">
<div class="page-title-wrapper">
<div class="page-title-txt">
<h1>Large Page Title</h1>
</div>
</div>
</div>
</section>
JS:
function checkWidth(){
var screenWidth = $window.width();
if( screenWidth <= 1280 ){
// Hd-ready desktop - 1280 x 720
$('[data-bg-lg]').each(function() {
var dataImg = $(this).attr('data-bg-lg');
$(this).css('background-image', 'url(assets/img/' + dataImg + ')');
});
} else if ( screenWidth >= 1281 && screenWidth <= 1920 ) {
// Full-hd desktop - 1920 x 1080
$('[data-bg-xl]').each(function() {
var dataImg = $(this).attr('data-bg-xl');
$(this).css('background-image', 'url(assets/img/' + dataImg + ')');
});
} else {
// Huge desktop - 2560 x 1440
$('[data-bg-xxl]').each(function() {
var dataImg = $(this).attr('data-bg-xxl');
$(this).css('background-image', 'url(assets/img/' + dataImg + ')');
});
}
}
The question now is how to check for a retina / non-retina display and serve the correct image set with the double resolution accordingly?
Upvotes: 2
Views: 2150
Reputation: 136
var query = "(-webkit-min-device-pixel-ratio: 2), (min-device-pixel-ratio: 2), (min-resolution: 192dpi)";
if (matchMedia(query).matches) {
// do high-dpi stuff
} else {
// do non high-dpi stuff
}
Upvotes: 0
Reputation: 14123
Check if window.devicePixelRatio
is higher than 1, and replace images with their high-resolution versions if it is.
Upvotes: 4