HRJ
HRJ

Reputation: 17767

Is there a way to intercept and block image loading from <img> elements?

Background

I have created a Javascript decoder for the FLIF image format. Since it's a new format and browsers don't support it yet (if ever), we want to create a poly-fill for it in JS.

We have one basic version already working. It queries for canvas elements and renders the FLIF image on to it.

However, for users that don't have Javascript enabled, the solution doesn't work. They see a blank canvas.

Question

We were wondering if there is a way to allow <img> elements to be specified in the HTML as a fall-back, but block them from loading via javascript, so that we can replace them with our FLIF canvas?

I have tried adding various event listeners, such as DOMContentLoaded, and removing the <img> elements in them, but by that time it is too late; the browser starts fetching the image.

Upvotes: 2

Views: 1522

Answers (4)

sergioFC
sergioFC

Reputation: 6016

I find this a bit hacky, but another choice is to add some extra info to the img tags, and then add some CSS from your poly-fill to avoid the images being showed.

Example HTML:

<img src="image.png" data-polyflif-src="image.flif">

Example CSS generated inside the poly-fill:

// Add CSS to avoid images marked as flif being showed
document.write("<style>img[data-polyflif-src]{display:none;}</style>");

// Once DOM is loaded generate the canvas element and content after every img tag (optionally remove the img or whatever)
...

Upvotes: 1

AJPerez
AJPerez

Reputation: 3595

You could place the <img> tags inside a <noscript> block.

I just did a test with Chrome, and it doesn't try to load the images inside the block (unless Javascript is disabled, of course). I don't know if every browser works the same way, though, some of them might still try to download the images.

Upvotes: 2

charlietfl
charlietfl

Reputation: 171669

You can't block an existing <img> tag from making the request for the resource set in src simply because the element has to exist before you can target it with script and by then the request has been made.

Note: Since 99% of the web requires script enabled anymore you could wrap the <img>'s in <noscript> tags

Upvotes: 2

Spencer Wieczorek
Spencer Wieczorek

Reputation: 21575

You cannot stop a standard image element from being requested in this case, as it's necessary to know that such an element exist before you can access it. Although you can remove/hide/etc the element as soon as possible, from the users end the image would of never been shown. For example:

<img id="foo" src="..." />
<script>
   document.getElementById("foo").remove();
</script>

Upvotes: 2

Related Questions