简体   繁体   中英

How to get remote image using jQuery asynchronously?

I want to show a remote image on my page. I use Bootstrap 2.3.2 Carousel. All the information comes from another web site's RSS feed. I get data into a div like the following:

...
<div id="newsItem-<?php echo $i;?>" class="item" data-src="<?php echo $feed[$i]->image; ?>" data-alt="<?php echo $feed[$i]->title; ?>">
</div>
...

The images takes too long to load. Page is loaded about 15 seconds. So I have decided to load images after the page loading finished.

There could be various dimensions of the pictures to be displayed. I want to show the largest existing one.

For each news item, all the images may have different but similar dimensions such as 1024x768, 620x350, 528x350, 527x350.

I have written a jQuery script to achieve this but something is wrong.

jQuery(function () {
    jQuery("div[id^='newsItem-']").each(function () {

        var r = jQuery(this).attr("data-src");
        var r620 = r.replace(".jpg", "-620x350.jpg");
        var r527 = r.replace(".jpg", "-527x350.jpg");
        var r1024 = r.replace(".jpg", "-1024x678.jpg");
        var r528 = r.replace(".jpg", "-528x350.jpg");
        var altImg = jQuery(this).attr("data-alt");

        if (pictureExists(r1024)){
            r = r1024;
        }
        else if (pictureExists(r620)){
            r = r620;
        }
        else if (pictureExists(r528)){
            r = r528;
        }
        else if (pictureExists(r527)){
            r = r527;
        }

        jQuery(this).prepend("<img src='" + r + "' alt='" + altImg + "' />");
        jQuery(this).removeAttr("data-alt");
        jQuery(this).removeAttr("data-src");
    });
});


function pictureExists(url) {
    var img = new Image();
    img.src = url;
    if (img.height !== 0) {
        return false;
    } else {
        return true;
    }
}

I want to display the largest existing picture in the carousel.

You cannot know the height/width of the image until its loaded. So its an async process.

In pictureExists function try to do it in this way:

/ Create new image
var img = new Image();

// Create var for image source
var imageSrc = "http://example.com/blah.jpg";

// define what happens once the image is loaded.
img.onload = function() {
// Stuff to do after image load ( jQuery and all that )
// Within here you can make use of src=imageSrc, 
// knowing that it's been loaded.
};

// Attach the source last. 
// The onload function will now trigger once it's loaded.
img.src = imageSrc;

If you want to use the above way then you will have to implement promise structure to tackle the async nature of the image load to fetch the height/width

Or you can use this small plugin. https://github.com/desandro/imagesloaded

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