Kyle Trauberman
Kyle Trauberman

Reputation: 25684

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?

Upvotes: 8

Views: 2364

Answers (6)

Rick Hitchcock
Rick Hitchcock

Reputation: 35670

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.

Upvotes: 1

user2594803
user2594803

Reputation:

Use

var string = '<img src="image.png">';

var matches = string.match(/src\=("|')(.*?)\1/);

console.log(matches[2]);

Upvotes: 1

blex
blex

Reputation: 25634

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

Upvotes: 2

Joe Czucha
Joe Czucha

Reputation: 4295

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.

Upvotes: 2

Varun
Varun

Reputation: 1946

If you just have the string , like <img src="image.jpg" /> why dont you go for regex?

Something like: /[\"\'][a-z0-9A-Z\.]*/. PS:My regex skills are poor,so you could manipulate it accordingly.

Upvotes: 1

Kyle Trauberman
Kyle Trauberman

Reputation: 25684

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.

Upvotes: 3

Related Questions