KeirDavis
KeirDavis

Reputation: 665

Loading images in jQuery

So here's the problem,

I'm trying to load images using jQuery to speed up the page downloading. To accomplish it, I have the following code as an image, which I want to load after the page loads.

<img src="/pixel.png" new-img="/newimage.png"/>

Then, to load the final image after the document fully loads, I've used the following.

$(document).ready(function(){ 
    $("img").attr("src", $("img").attr("new-img"));
});

This works fine for a single image, except I have multiple images that I want to convert to this. I'm completely stumped as when I try and load multiple images like this, it sets all the images to the last image loaded.

I'm not sure, but does '$(this)' have anything to do with it?

JSFiddle: http://jsfiddle.net/AeroMcDoom/8sxED/

Upvotes: 2

Views: 109

Answers (5)

NickHTTPS
NickHTTPS

Reputation: 799

I think you can save an extra HTTP request by doing this:

<div class="lazy">
  <img src="data:image/gif;base64,R0lGODlhAQABAIAAAAAAA ///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7"
    data-src="/newimage.png"
    alt="Good to go" />
</div>

And the JS:

$(window).on('load', function() {

   $(".lazy > img").each(function(){
      var src = $(this).attr('data-src');

      $(this).attr('src',src);
   });
}); 

Upvotes: 0

MildlySerious
MildlySerious

Reputation: 9190

With a little less overhead:

$(function(){ 
    $("img").each(function(){
        this.src = this.getAttribute('data-newimg');
    });
});

There is no need to initialize jQuery one or two times per image for this, unless you need this to work on IE6.

Upvotes: 0

Miquel Las Heras
Miquel Las Heras

Reputation: 760

$(document).ready(function(){ 
    $("img").each(function(){
      $(this).attr('src',$(this).attr("new-img"));
    });
});

Upvotes: 0

RononDex
RononDex

Reputation: 4183

Try this:

$("img").each(function(){$(this).attr("src", $(this).attr("new-img"))});

.attr on a selector that matches more than one element won't work as you do it. .attr() will set the attribute of all images its find to the defined content. Also you can't set it using $("img").attr("new-img") because .attr() always returns only the first value it finds from the selector.

Upvotes: 1

A. Wolff
A. Wolff

Reputation: 74410

Use that:

$("img").attr("src", function(){return $(this).attr("new-img")});

FYI, you should use data-* attribute instead:

<img src="/pixel.png" data-img="/newimage.png"/>

And then:

 $("img").attr("src", function(){return $(this).data("img")});

Upvotes: 6

Related Questions