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
/
so after the snippet jQuery, it bees like
<img src='.jpg' />
Any help is greatly appreciated.
so far I wrote something like
$().ready(function(){
var cdn ='';
$('img').attrib('src', cdn);
});
However it is replaced the src rather than pre
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./
so after the snippet jQuery, it bees like
<img src='http://cdn.something./img/picture1.jpg' />
Any help is greatly appreciated.
so far I wrote something like
$().ready(function(){
var cdn ='http://cdn.something.';
$('img').attrib('src', cdn);
});
However it is replaced the src rather than pre
Share Improve this question edited Jan 27, 2011 at 11:12 jAndy 236k57 gold badges313 silver badges363 bronze badges asked Jan 27, 2011 at 10:53 dbwebtekdbwebtek 2453 silver badges5 bronze badges3 Answers
Reset to default 8it'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.' + 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.' + 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.
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.
Depending what your specific problem is, you might be able to sort out this problem with a base tag, but I assume you will only want this on images, but changing the src once the page has loaded will make the images reload? IF the images don't exist in the current location you will need to change the src attribute before the page is loaded (server side).