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
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.