Skip to content

Instantly share code, notes, and snippets.

@williammalo
Forked from 140bytes/LICENSE.txt
Last active March 1, 2019 17:39
Show Gist options
  • Save williammalo/3077264 to your computer and use it in GitHub Desktop.
Save williammalo/3077264 to your computer and use it in GitHub Desktop.
Responsive image loading in 199bytes (minification help needed)

This function loops through all images on the page, and serves the appropriately sized image file from a list in a data attribute.

example link: http://total.maloweb.com/responsive

example html:

<img src="default.png" data-widths="400,600,800,1023" data-srcsuffix="-foo.png">

example javascript:

onload=onresize=function(){
    respImg("data-widths","data-srcsuffix")
}

example filenames:

400-foo.png
600-foo.png
800-foo.png
1023-foo.png
function(x,y, //x:attribute name for widths, y:attribute name for suffix
a,c,d,b,e,f,g){ //placeholders
for(d in f=document.images)if(a=f[d],g=a.getAttribute(x)){ //for every image with a width list
b=g.split(","); //split width list into array
for(c=b.length;c--;) //for every width
if(e=b[0],b[c]<a.offsetWidth){ //set lowest width as default(e), when the loop encounters a width smaller than the image:
e=b[c+1]||b[c];break} //set e to one width higher, or the highest width available
a.src=e+a.getAttribute(y) //set src attribute to the right width
}
}
function(x,y,a,c,d,b,e,f,g){for(d in f=document.images)if(a=f[d],g=a.getAttribute(x)){b=g.split(",");for(c=b.length;c--;)if(e=b[0],b[c]<a.offsetWidth){e=b[c+1]||b[c];break}a.src=e+a.getAttribute(y)}}
{
"name": "respImg",
"description": "Responsive image loading",
"keywords": [
"responsive",
"conditional",
"image",
"loading"
]
}
<!DOCTYPE html>
<title>Foo</title>
<a href="http://total.maloweb.com/responsive">click link for example</a>
@shinsenter
Copy link

My idea 136 bytes: (posted from my phone, not tested)

function respImg(s,u,d,l){document.images.map(a=>{d=a.dataset,for(l=d[s].split(',');l.length||a.offsetWidth>w=l.shift();)a.src=w+d[u]})}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment