Asked  7 Months ago    Answers:  5   Viewed   62 times

I want to load external images on my page asynchronously using jQuery and I have tried the following:

$.ajax({ 
   url: "http://somedomain.com/image.jpg", 
   timeout:5000,
   success: function() {

   },
   error: function(r,x) {

   }
});

But it always returns error, is it even possible to load image like this?

I tried to use .load method and it works but I have no idea how I can set timeout if the image is not available (404). How can I do this?

 Answers

42

No need for ajax. You can create a new image element, set its source attribute and place it somewhere in the document once it has finished loading:

var img = $("<img />").attr('src', 'http://somedomain.com/image.jpg')
    .on('load', function() {
        if (!this.complete || typeof this.naturalWidth == "undefined" || this.naturalWidth == 0) {
            alert('broken image!');
        } else {
            $("#something").append(img);
        }
    });
Tuesday, June 1, 2021
 
tdous
answered 7 Months ago
98

Here's what we did and its working great. We skipped setting src attribute of img and added img-location to a fake attribute lsrc. Then we load a dynamic image with lsrc value, and set the src of actual image only after its loaded.

Its not about faster loading, but its about showing the images only when its downloaded completely on your page, so that user do not have to see that annoying half-loaded images. A placeholder-image can be used while the actual images are being loaded.

Here's the code.

 $(function(){
    $.each(document.images, function(){
               var this_image = this;
               var src = $(this_image).attr('src') || '' ;
               if(!src.length > 0){
                   //this_image.src = options.loading; // show loading
                   var lsrc = $(this_image).attr('lsrc') || '' ;
                   if(lsrc.length > 0){
                       var img = new Image();
                       img.src = lsrc;
                       $(img).load(function() {
                           this_image.src = this.src;
                       });
                   }
               }
           });
  });

Edit: Trick is to set the src attribute only when that source is loaded in temporary img. $(img).load(fn); handles that.

Monday, June 28, 2021
 
Extrakun
answered 6 Months ago
95

See bellow the answer what I got back from jQuery team. Ticket #8298: http://bugs.jquery.com/ticket/8298

Answer:

After checking your report and your code samples I come to the conclusion that this isn't a bug. I also made this test case jQuery 1.4+ (until 1.5) had a bug which caused the cache option not to default to false for script requests. This bug (see #7578) has been fixed in 1.5 . Now what you might know or not know is, that jQuery does special-handle script tags when doing DOM manipulations (to prevent certain errors in IE). It filters them out and requests them via ajax. This explains why even a "normal" inline script tag suddenly is requested with additional url parameters. There are ways to work around this if it has unwanted side effects for you.

  1. use $.ajaxSetup({ cache: true }) when appropriate

  2. use a prefilter for script requests and e.g. check for urls where you don't want the random parameter to be added and set cache: true in the prefilter for those

  3. in e.g. the success call back handle the script tags yourself by doing something along these..

..lines:

var elems = $(htmlwithscripttags);
elems.filter("script") //now do whatever with the scripts
elems.filter(":not(script)").appendTo("body"); //e.g.
Tuesday, August 3, 2021
 
ramdemon
answered 5 Months ago
84

Set the load handler first, then set the src.

fullImage.bind('load', function() {
   ...
}).attr('src', fullImageUrl);
Friday, August 13, 2021
 
Manju
answered 4 Months ago
48

I think it works but its attempting to inline the write which I don't know if that would work in this case.

You would need to see if there was a way to essentially execute the '.getHTML' method and take that result and update an existing element on the page.

The issue though is that the anonymous function that is generated and executed inline might not work properly.

Monday, December 6, 2021
 
samrap
answered 3 Days ago
Only authorized users can answer the question. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :  
Share