简体   繁体   中英

How to optimize background-image similar to <picture> tag?

I make a website and download speed is extremely important, especially for mobile devices. How can I optimize the loading of images as we do with tag, but for background-image in 'style' attribute?

you can use javascript..

get width/height of screen with java script, put it in variable and do if statements and then set styling of element.

var width = window.innerWidth
|| document.documentElement.clientWidth
|| document.body.clientWidth;

if(width>700){
document.getElementById("id").style.background="url('image.png')";
}

u add as many if statements as you need, similar to @meda queries

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM