Skip to content

Instantly share code, notes, and snippets.

@hallvors
Created September 13, 2013 12:11
Show Gist options
  • Save hallvors/6549877 to your computer and use it in GitHub Desktop.
Save hallvors/6549877 to your computer and use it in GitHub Desktop.
How Wikipedia implements srcset in js
$.fn.hidpi=function(){
var $target=this,devicePixelRatio=$.devicePixelRatio(),testImage=new Image();
if(devicePixelRatio>1&&testImage.srcset===undefined){
$target.find('img').each(function(){
var $img=$(this),srcset=$img.attr('srcset'),match;
if(typeof srcset==='string'&&srcset!==''){
match=$.matchSrcSet(devicePixelRatio,srcset);
if(match!==null){
$img.attr('src',match);
}
}
}
);
}
return $target;
}
;
$.matchSrcSet=function(devicePixelRatio,srcset){
var candidates,candidate,bits,src,i,ratioStr,ratio,selectedRatio=1,selectedSrc=null;
candidates=srcset.split(/ *, */);
for(i=0;
i<candidates.length;
i++){
candidate=candidates[i];
bits=candidate.split(/ +/);
src=bits[0];
if(bits.length>1&&bits[1].charAt(bits[1].length-1)==='x'){
ratioStr=bits[1].substr(0,bits[1].length
-1);
ratio=parseFloat(ratioStr);
if(ratio<=devicePixelRatio&&ratio>selectedRatio){
selectedRatio=ratio;
selectedSrc=src;
}
}
}
return selectedSrc;
}
;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment