Nrc
Nrc

Reputation: 9787

JQuery Ajax, load img

To load a img with jQuery and Ajax

1- I try to load the img directly, it does not work:

$("#target").load("img.jpg");

2- I can load a img that is inside another html. Here I load in the div target the img that is inside img1 inside img.html:

$(function(){
   $("#linkajax").click(function(e){
      e.preventDefault();
      $("#target").load("img.html #img1");     
   });
})

Is the 2 the best way to load a img with Ajax and jQuery or there is a better, more direct way ?

(I am using Ajax because I need to load a lot of img. I want to load first and then fadeIn fast just when the user click. I simplify the case here just to explain it better)

Upvotes: 1

Views: 1088

Answers (3)

Petr Čihula
Petr Čihula

Reputation: 997

Seems to me like you need to preload all the images for a faster display. There's no need to use ajax for that. Just create an Image object and apply all your urls to it consecutively. This way your browser will cache all of them and when asked, just serve them from the cache.

var img = new Image(),
    urls = ['images/image.jpg','images/image2.jpg'],
    imgIdx = 0;

img.onload = function() {
    imgIdx++;
    if (imgIdx < urls.length) img.src = urls[imgIdx];
}

img.src = urls[imgIdx];

Upvotes: 0

dnagirl
dnagirl

Reputation: 20456

Why do you need ajax to refer to an image file?

$('#target').append('<img src="img.jpg" alt="my image"/>');

ETA: If you want to retrieve a list of image paths via ajax, then something like this would be appropriate:

$('#linkajax').on('click ', function(){
  $.ajax({
     url: "getsrcs.php", //or some script to return a JSON array
     dataType: 'json',  
  }).done(function(data) { //where data is a JSON array like [img1.jpg, img2.jpg ...]
       $(data).each(function(){
         var img = $(' < img src = "'+this+'" / > ');
         $('#target ').append(img);//you can put your fade effect here if you like
       });
    }
  );  
});

Upvotes: 1

epascarello
epascarello

Reputation: 207511

Why are you doing that, just append an image.

$("#target").append("<img src='img.jpg' />");

other way

$('<img/>', {
    src: 'img.jpg'
}).appendTo("#target");

Upvotes: 1

Related Questions