Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

const noScriptEl = document.createElement("noscript");
const imgEl = document.createElement("img");
imgEl.src = "https://placehold.co/1";
document.body.appendChild(noScriptEl).appendChild(imgEl);
<p>The 20x20 should always make a network request
<img src="https://placehold.co/20" 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 = 'http://placekitten.com/20/20';
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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading