2

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/

1

5 Answers 5

6

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")});
Sign up to request clarification or add additional context in comments.

2 Comments

What? you can use a function as the second parameter in attr()? Game changer!
@CerylWiltink Ya, check DOC: .attr( attributeName, function(index, attr) ) api.jquery.com/attr/#attr-attributeName-functionindex--attr
1

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.

Comments

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

Comments

0

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.

Comments

0

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);
   });
}); 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.