简体   繁体   中英

jQuery to prepend URL in img src attribute

I just need a jQuery snippet to do the prepend in img src , ie

<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

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 the DOMready 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.

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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM