background-size:cover performance issues

2020-03-30 18:01发布

问题:

I'm having performance issues (especially in Safari) with using a large number of elements with background-size: cover. I've added transform: translate3d(0,0,0) which did help a little, but not as much as I'd like. I'm really looking for a pure css fix if possible.

回答1:

jsFiddle Demo

background-size:cover has terrible performance across the board. I have found many issues with using it before, and have abandoned it in favor of this approach.

Use an image inside of the div, size the div to the dimensions you wish to use. Have the image sized as such:

left:0;
right:0;
top:0;
bottom:0;
position:relative;
width:100%;
height:100%;

And directly assign the url of the image being loaded to src="url".

You can see even with this strenuous test that it does just fine (even when tested in safari - jQuery used for brevity in demo)

var place = "http://placehold.it/";
var all = $("<div>");
for( var w = 5; w < 100; w++ ){
 for( var h = 5; h < 100; h++ ){
  var nwln = $('<div>');
  var img = $('<img class="sq">');
  nwln.width(w*2);
  nwln.height(h*2);
  var url = place + w + "x" + h;
  img[0].src = url;
  nwln.append(img);
  all.append(nwln);
 }
}
$("#grid").append(all);