Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to prevent an <img> tag from loading its image?

I have the following script which take a string with html information (containing also reference to images).

When I create a DOM element the content for the image is being downloaded by the browser. I would like to know if it is possible to stop this Beauvoir and temporary prevent loading.

I am targeting web-kit and presto browsers.

  relativeToAbosluteImgUrls: function(html, absoluteUrl) {
        var tempDom = document.createElement('div');
        debugger
        tempDom.innerHTML = html;
        var imgs = tempDom.getElementsByTagName('img'), i = imgs.length;
        while (i--) {
            var srcRel = imgs[i].getAttribute('src');
            imgs[i].setAttribute('src', absoluteUrl + srcRel);
        }
        return tempDom.innerHTML;
    },
like image 301
GibboK Avatar asked Oct 03 '13 13:10

GibboK


1 Answers

Store the src path into an HTML5 data-* attribute such as data-src. Without src being set, the browser will not download any images. When you are ready to download the image, simply get the URL from the data-src attribute and set it as the src attribute

$(function() {
    // Only modify the images that have 'data-src' attribute
    $('img[data-src]').each(function(){
        var src = $(this).data('src');
        // modify src however you need to, maybe make
        // a function called 'getAbsoluteUrl'
        $(this).prop('src', src);
    });
});
like image 142
lightswitch05 Avatar answered Sep 21 '22 02:09

lightswitch05