If you're injecting the html snippet of the image element, you could put it in a span rather and manipulate the html later.
For example:
<div id="topNav">
<span class="unloaded">
<noscript>
<img src="https://www.jpl.nasa.gov/images/universe/20170802/heliophysics-16.jpg">
</noscript>
</span>
<div class="heightTest">
</div>
<span class="unloaded">
<noscript>
<img src="https://www.jpl.nasa.gov/images/universe/20170802/heliophysics-16.jpg">
</noscript>
</span>
</div>
Then watch it with javascript:
function isElementInViewport (el) {
var rect = el.getBoundingClientRect();
return (
rect.top >= 0 &&
rect.left >= 0 &&
rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) &&
rect.right <= (window.innerWidth || document.documentElement.clientWidth)
);
}
var images = document.getElementsByClassName('unloaded');
function checkImages() {
var clean = false;
for(var i=0; i<images.length;i++){
var el = images[i];
if(isElementInViewport(el)){
//replace the span's innerhtml with the noscript innerhtml.
el.innerHTML = el.childNodes[1].innerHTML;
//remove the class, since it's now loaded.
el.classList.remove("unloaded");
//we changed at least one element, so we'll want to get a new clean list.
clean = true;
}
}
if(clean == true){
images = document.getElementsByClassName('unloaded');
}
}
checkImages();
window.addEventListener('scroll', checkImages, false);
This way you're waiting until the event to modify any HTML. An advantage here is if javascript isn't running, the images will load anyways. As well since it's a span you can set the size and background to a grey loading icon via css for the span class "unloaded".
srctodata-src. For big blob of HTML, it may matter. Maybe a global substring will help.