-2

How can I change my image url to CDN URL using JavaScript or jQuery

For example urls in my webpage are

https://example.com/img/img.jpg

Then it should be replaced by

https://mycdn.com/https://example.com/img/img.jpg
Mi-Creativity
  • 9,554
  • 10
  • 38
  • 47
Punit Makwana
  • 17
  • 1
  • 3
  • `img.setAttribuge('src', "//mycdn.......")` – Rajesh May 17 '17 at 06:18
  • 1
    Possible duplicate of [Changing the image source using jQuery](http://stackoverflow.com/questions/554273/changing-the-image-source-using-jquery) – Rajesh May 17 '17 at 06:18
  • $('img').attr('src','https://mycdn.com/'+$('img').attr('src')); – JYoThI May 17 '17 at 06:20
  • Remember, you might end up loading the images twice (once from your server and once from the CDN) if you use jQuery as its initialised after the page has finished loading. Using plain javascript might be better, but ideally this should be done on the backend. – bcosynot May 17 '17 at 06:20
  • you have to change in one place on at any event to any signle place – sunil May 17 '17 at 06:27

1 Answers1

1

Consider following snippet:

$('img').each(function(){
    var img = $(this);
    var srcOld = img.attr('src');
    var srcNew = 'https://mycdn.com/' + srcOld;
    img.attr('src', srcNew); // Updating src here
});

Explanation: The above snippet loops to each img element and updates src of each one. Whereas this way HTML page will load all images twice first for local images and then CDN images. Better way to update src from backend.

Manwal
  • 23,450
  • 12
  • 63
  • 93
  • Should you not mark it as dupe? Also, its a bad practice to add protocol in url – Rajesh May 17 '17 at 06:25
  • 2
    This is not exact duplicate. OP wants to change for all images. Its better to clarify it before deciding duplicate. – Manwal May 17 '17 at 06:27