JSFiddle - React, Tailwind, and code Playground
HTML
<div id="coolSection" class="bgFromSrcSet">
<img class="srcSet"
src="https://webkit.org/demos/srcset/image-src.png"
srcset="https://webkit.org/demos/srcset/image-1x.png 1x,
https://webkit.org/demos/srcset/image-2x.png 2x,
https://webkit.org/demos/srcset/image-3x.png 3x,
https://webkit.org/demos/srcset/image-4x.png 4x"
>
Something else...
</div>
CSS
.srcSet{
position: fixed;
z-index: 0;
z-index: -1;
z-index: -100;
visibility: hidden;
}
#coolSection{
width: 300px;
height: 300px;
position: absolute;
top: 50%; left: 50%;
margin-top: -150px; margin-left: -150px;
background-color: #fff;
}
JavaScript
jQuery(function($){ //ON DOCUMENT READY
var $window = $(window); //prepare window as jQuery object
var $srcSets = $('.srcSet'); //get all images with srcSet clas
$srcSets.each(function(){ //for each .srcSet do...
var $currImg = $(this); //prepare current srcSet as jQuery object
$currImg
.load(function(){ //bind the load event
var img = $currImg.get(0); //retrieve DOM element from $currImg
//test currentSrc support, if not supported, use the old src
var src = img.currentSrc ? img.currentSrc : img.src;
//To the closest parent with bgFromSrcSet class,
//set the final src as a background-image CSS
$currImg.closest('.bgFromSrcSet').css('background-image', "url('"+src+"')");
//remove processed image from the jQuery set
//(to update $srcSets.length that is checked in the loadChecker)
$srcSets = $srcSets.not($currImg);
$currImg.remove(); //remove the <img ...> itself
})
;
});
//window's load event is called even on following loads...
$window.load(function(){
//prepare the checker
var loadChecker = setInterval(function(){
if( $srcSets.length > 0 ) //if there is still work to do...
$srcSets.load(); //...do it!
else
clearInterval(loadChecker); //if there is nothing to do - stop the checker
}, 150);
});
});