Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to prevent a <img src="url"> to be loaded, with CSS?

Tags:

html

css

image

Let's say I have an image like this:

<img src="https://via.placeholder.com/150" class="abcd" />

How to make, with CSS only, that the url https://via.placeholder.com/150 is never loaded?

I tried:

  1. .abcd { display: none; }: a GET to the image is still done (you can check with the browser's Developer Tools > Network)

  2. .abcd { visibility: hidden; }: idem

  3. put the <img> inside a <div> which is itself in display: none;: idem, a GET request is still done for the image

  4. I tried the method from Is it possible to set the equivalent of a src attribute of an img tag in CSS?:

    .abcd { content:url("https://via.placeholder.com/200"); }
    

    but then both https://via.placeholder.com/150 and https://via.placeholder.com/200 were loaded.

  5. .abcd { content: none; } didn't work either


Application: I'm trying to do a 1px-tracking-system for emails, and I want to prevent my own views to be tracked by injecting a custom CSS (with Stylus chrome extension, uBlockOrigin)

Note: Of course, I already read Does "display:none" prevent an image from loading? but it did not give an exact solution for this linked problem.

like image 890
Basj Avatar asked Nov 06 '22 11:11

Basj


2 Answers

Many tests have been done by Tim Kadlec on this page.

In short, images with <img>:

<div id="test1"><img src="images/test1.png" alt="" /></div>

will always be loaded even with:

#test1 { display:none; }

Instead, using a div with background-image like this:

<div id="test1"><div style="background-image: url('https://via.placeholder.com/159');"></div></div>

will allow the image to NOT be loaded when using #test1 { display:none; }.

like image 169
Basj Avatar answered Nov 11 '22 03:11

Basj


Application: I'm trying to do a 1px-tracking-system for emails, and I want to prevent my own views to be tracked by injecting a custom CSS (with Stylus chrome extension, uBlockOrigin)

Why you don't do the opposite and have the image not loading by default then you load it when needed.

Here is an idea using CSS variables

img {
  content:var(--img);
}

/* The CSS to disable the loading
img {
  --img:initial!important;
}
*/
<img style="--img:url('https://via.placeholder.com/150')" class="abcd" />

Another idea without CSS variables where the image will load by default. Make sure to load the CSS early to avoid the loading.

/*to disable the loading. Make sure it's considered before the inline style
img {
  content: none!important;
}
*/
<img style="content:url('https://via.placeholder.com/150')" class="abcd" />
like image 37
Temani Afif Avatar answered Nov 11 '22 04:11

Temani Afif