Nested <img> within <noscript> still making network request

I have a JavaScript-generated <img> within a <noscript>. I would expect that there is no network request for the image unless JavaScript was disabled. However, I’m seeing both network requests occur (when I would only expect one).

What am I not understanding?

Here’s a Codepen rep
enter image description here

const noScriptEl = document.createElement("noscript");
const imgEl = document.createElement("img");
imgEl.src = "";
<p>The 20x20 should always make a network request
<img src="" alt=""></p>

<p>The JS added 1x1 shouldn't make any network request</p>

>Solution :

Dynamically generated image elements always load their source, even if the element isn’t added to the DOM.

const img = document.createElement('img');
img.src = '';
img.onload = function () { console.log(this.width); } 
/* The browser can't calculate the width of the image unless  
   it accesses it over the network. Since it shows the width,
   we know it accesses it over the network. */

Consequently, adding such an image to the DOM in a place where it usually wouldn’t be loaded has no influence over it being loaded or not.

Leave a Reply