Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get image src without loading the image?

I have a html snippet being returned through ajax. The snippet is an <img> tag.

<img src="image.jpg" />

I need to extract the value of the src attribute without loading the image initially. The reason for this is the src attribute contains a partial path that I need to manipulate in my app to load the image properly.

I have the following code currently extracting the src attribute:

var src = $(value).attr('src');

However, this causes the image to load, resulting in a 404. I would like to avoid this unnecessary request.

How can I extract the value of the src attribute without causing the browser to load the image?

like image 275
Kyle Trauberman Avatar asked Jun 30 '15 19:06

Kyle Trauberman


4 Answers

I solved this by changing the name of the src attribute before loading it into jquery.

 value = value.replace('src', 'data-src');
 var src = $(value).attr('data-src');

Doing this allows me to extract the value without causing the browser to attempt to load the images.

like image 186
Kyle Trauberman Avatar answered Sep 21 '22 23:09

Kyle Trauberman


Your best bet is probably to output a data tag on the image. You can then manipulate this using jQuery and then use it to write the final image path.

So you'd do something like this in your HTML:

<img data-img-src="abc.jpg" class="my-image" />

Then in your jQuery:

var path = $('.my-image').data('img-src');
console.log(path); // Do something here, then write the new path with:
$('.my-image).attr('src', new_path);

EDIT: Sorry I just re-read the bit where it's coming via AJAX. In that case, you can probably use the data callback of your ajax request to strip the src from the image.

like image 42
Joe Czucha Avatar answered Sep 21 '22 23:09

Joe Czucha


$.ajax('someURL.html', function(data){
    var html = data.replace(/\ssrc/g, ' data-src'),
        img  = $(html),
        src = 'some/path/' + img.data('src');
    img.attr('src', src);
    $('#container').append(img);
});
like image 45
blex Avatar answered Sep 20 '22 23:09

blex


You can simply remove the attribute after accessing it.

This will not load the invalid image, as you can confirm in your console:

var s= $('<img src="invalidURL.jpg">'),
    src= s.attr('src');

s.removeAttr('src');
console.log(src);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Remove removeAttr(), and it will attempt to load the image.

like image 44
Rick Hitchcock Avatar answered Sep 20 '22 23:09

Rick Hitchcock