Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery to prepend URL in img src attribute

I just need a jQuery snippet to do the prepend in img src , i.e

<img src='/img/picture1.jpg' />

The code snippet jQuery is to prepend this url

http://cdn.something.com/ 

so after the snippet jQuery, it becomes like

<img src='http://cdn.something.com/img/picture1.jpg' />

Any help is greatly appreciated.

so far I wrote something like

$().ready(function(){
     var cdn ='http://cdn.something.com';
   $('img').attrib('src', cdn);

});

However it is replaced the src rather than pre

like image 319
dbwebtek Avatar asked Dec 17 '22 18:12

dbwebtek


2 Answers

it's not really jQuery related, anyway you could do it with .attr()what is that?:

$('img').attr('src', function(index, src) {
     return 'http://cdn.something.com' + src;
});

This would affect all of your <img> nodes in your markup and replace the src.

Anyway, I'm not so sure that this is a great idea. At the time theDOMready event fires, a browser might already have tried to access the old source attribute. If you must do this in Javascript, it's probably a better idea to store the path info within a custom data attribute so a browser is not tempted to load the image. This could look like:

HTML

<img src='' data-path='/img/picture1.jpg' />

JS

$(function() {
    $('img').attr('src', function(index, src) {
       return 'http://cdn.something.com' + this.getAttribute('data-path');
    });
});

This should do it. You could replace this.getAttribute() by $(this).data('path') since jQuery parses those data attributes into it's "node" data hash. But this would create another jQuery object, which really is unecessary at this point.

like image 149
jAndy Avatar answered Dec 19 '22 06:12

jAndy


This should work:

$.ready(function() {
    $('img').each(function() {
        $(this).attr('src', cdn + $(this).attr('src'));
    });
});

However I'm not sure it is the good solution for using a CDN, as the browser will have already tried to load the images from your server at the time the script will be called.

You should do this on the server side instead.

like image 23
Arnaud Le Blanc Avatar answered Dec 19 '22 07:12

Arnaud Le Blanc