JQuery to add url to img src attribute

I just need a jQuery snippet to make preend in img src, i.e.

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

JQuery code snippet should add this url

 http://cdn.something.com/ 

so after jQuery fragment it becomes like

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

Any help is greatly appreciated.

so far i have written something like

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

});

However, it replaces src, not pre

+4
source share
3 answers

It's not very similar to jQuery, anyway, you can do it with .attr() what is it? :

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

This will affect all your <img> nodes in your markup and replace src .

In any case, I'm not sure if this is a great idea. During the DOMready event, the browser may have already tried to access the source attribute old . If you need to do this in Javascript, it might be better to store the path info in the user data attribute so that the browser does not want to load the image. It might look like this:

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'); }); }); 

That should do it. You can replace this.getAttribute() with $(this).data('path') since jQuery parses these data attributes into "node" hash data. But this would create another jQuery object that is not needed at the moment.

+8
source

This should work:

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

However, I'm not sure if this is a good solution for using CDN, as the browser has already tried to download images from your server during the script call.

You must do this on the server side.

+4
source

Depending on your specific problem, you can solve this problem with the base tag, but I assume that you only need this on the images, but changing src after loading the page will reload the images? If the images do not exist at the current location, you will need to change the src attribute before the page loads (server side).

0
source

Source: https://habr.com/ru/post/1337294/


All Articles