Chrome / Safari image loader, first time opening

2019-07-03 23:17发布

问题:

Built my own image slider, works perfectly inside firefox. Yet in chrome / safari the images tend to not load the first time the page is opened. (if you refresh everything is fine)

var count = $("#show-image img").size();
var img = $("#show-image img");
$(document).ready(function () {
for(i=0;i<count;i++){
    var width = img[i].width;
    var height = img[i].height;
    $(img[i]).css({"width": width, "height": height});
    console.log(img[i].width);
}
});

In chrome and safari, the first time the page loads some of the images are getting the height and width set to 0px. I'm assuming cause the images aren't fully loaded yet.

How is it possible to run the code, when page is ACTUALLY fully loaded?

回答1:

As a quick and simple solution, use .load() instead.

A better solution would be to use this jQuery plugin:

$(document).ready(function() {
    $('#show-image').imagesLoaded(function() {
        /* your code here */
    });
});

The advantage being that you only have to wait for those specific images to be loaded, instead of everything as you would for .load().