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:
.abcd { display: none; }
: a GET to the image is still done (you can check with the browser's Developer Tools > Network
)
.abcd { visibility: hidden; }
: idem
put the <img>
inside a <div>
which is itself in display: none;
: idem, a GET request is still done for the image
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.
.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.
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; }
.
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" />
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With