Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript to cancel image loading

Tags:

javascript

dom

I am looking for a way to cancel image loading using javascript. I've looked at other questions and hiding them is not enough. Also, the rest of the page must load (window.stop() is out of the question).

The page that is being loaded is not under my control, only one thing is guaranteed - the first <script> on the page is my javascript (lightweight - no jquery).

I have tried setting all img sources to nothing, that did not help since the dom is created after the page is parsed, and all browsers have the same behavior - the img is loaded once it is parsed.

like image 753
daniel_or_else Avatar asked Feb 27 '26 02:02

daniel_or_else


2 Answers

Not possible with modern browsers. Even if you alter the src attribute of image tag with JavaScript browsers still insist on loading the images. I know this from developing the Lazy Load plugin.

like image 159
Mika Tuupola Avatar answered Feb 28 '26 17:02

Mika Tuupola


The only way I can see to stop images loading is to not have an src attribute present in the image itself, and using a custom data-* attribute to hold the location of the image:

<img data-src="http://path.to/image.png" />

Obviously this doesn't gracefully degrade for those (admittedly rare) JavaScript disabled browsers, and therefore requires a noscript fall-back:

<img data-src="http://path.to/image.png" />
<noscript><img src="http://path.to/image.png" /></noscript>

And couple this with a simple function to load the images when you, or your users, are ready for them:

/* simple demo */
function imagePopulate(within, attr) {
    within = within && within.nodeType == 1 ? within : document;
    attr = attr || 'data-src';
    var images = within.getElementsByTagName('img');
    for (var i = 0, len = images.length; i < len; i++) {
        if (images[i].parentNode.tagName.toLowerCase() !== 'noscript') {
            images[i].src = images[i].getAttribute(attr);
        }
    }
}

document.getElementById('addImages').onclick = function(){
    imagePopulate();
};

JS Fiddle demo.

I can't be sure for all browsers, but this seems to work in Chrome (in that there's no attempt, from looking at the network tab of the developer tools, to load the noscript-contained img).

like image 45
David Thomas Avatar answered Feb 28 '26 16:02

David Thomas