jQuery to prepend URL in img src attribute

后端 未结 3 1735
有刺的猬
有刺的猬 2021-01-06 10:54

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


The code snippet jQuery is to prepe

相关标签:
3条回答
  • 2021-01-06 11:39

    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.

    0 讨论(0)
  • 2021-01-06 11:41

    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.

    0 讨论(0)
  • 2021-01-06 11:54

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

    0 讨论(0)
提交回复
热议问题