Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Try to stop image loading with javascript

is there a way to halt the image download with javasript? I would like to extract all urls from the image tags and start the image loading only when the user scrolls to a specific one. I know that I can stop the download via

window.stop()

But by using this workaround the browser stops also loading the background images which are defined in the CSS file(s).

So is there a way to achieve this without implementing a "markup workaround" such as "including the image url into a span or something".

like image 818
notion Avatar asked Nov 14 '22 17:11

notion


1 Answers

You can remove the src attribute entirely using JavaScript, this will effectively stop the images from being downloaded.

var img = document.getElementById('imageID'),
    src = img.getAttribute('src');

img.removeAttribute('src');

This will ensure your images will still be loaded if a user has JS disabled, because you are removing the src attributer later on using JS.

You can then store the url in a variable and set it back when you want to load them again.

img.setAttribute('src', src);

The key point it not leaving an empty src attribute (src=""), otherwise it will be treated by the browser as '/', actually trying to load your home page and store it in the image element. You have to remove the src attribute entirely.

like image 178
Jose Faeti Avatar answered Dec 15 '22 13:12

Jose Faeti