Reputation: 17485
I want to get smarter with how my background images are selected and loaded, based on how large the screen is / can get.
Currently, I am using a combination of pre-loading js and css to deliver a low-res background image and then swapping it for a high-res once its loaded, like so:
.bg {
position: relative;
background-size: cover;
background-position: center;
background-color: grey;
background-repeat: no-repeat;
background-image: url('lowres.jpg');
/* add in some media queries here to choose different lowres cropping etc */
}
.bg.highres {
background-image: url('highres.jpg');
/* add in some media queries here to choose different highres cropping etc */
}
#highres-loader {
display: none;
}
and, in my html:
<div id="highres-loader">
<img src="highres.jpg" onload="add_highres_class_to_background_image_after_it_loads()">
</div>
<div class="bg"></div>
This allows a low-res image to be displayed right away, while the high-res loads in the background. And, with media queries, I can combine the above to ensure the proper bg image loads for the device. Looks great!
However, what I find happening is: 1) I cannot prioritize the large images to necessarily load AFTER the rest of the site completes. Ideally, it would be better to serialize it. Also, this scheme multiplies out the number of images downloaded, which is unsatisfactory, and I think even if they aren't used.
As I was writing this question, I came upon some research here: https://timkadlec.com/2012/04/media-query-asset-downloading-results/ that looks like I should be taking into account. However the report is dated now, so I'm not sure what the research would reveal today.
Upvotes: 0
Views: 971
Reputation: 15786
I think your approach is correct but you want to make sure the high-res images start loading once the page is accessible. I've done a lot of research on this and found the below is the only way that's working.
<script type="text/javascript">
function downloadAtOnload() {
// Dynamically load CSS
var ls = document.createElement("link");
ls.rel="stylesheet";
ls.href= "css/my-css.css";
document.getElementsByTagName("head")[0].appendChild(ls);
// Dynamically load Javascript/jQuery
element = document.createElement("script");
element.src = "js/my-js.js";
document.body.appendChild(element);
}
if (window.addEventListener) window.addEventListener("load", downloadAtOnload, false);
else if (window.attachEvent) window.attachEvent("onload", downloadAtOnload);
else window.onload = downloadAtOnload;
</script>
Inside the my-js.js script you can load the high-res image and put it inside the correct container.
Upvotes: 1