Load smaller image in first with Javascript

How to avoid images popping in after the page has loaded by loading in and displaying a much smaller one first.

Credit to FThompson here at StackOverflow. I edited it for use with PHP but the basic version is as follows.

The image tag, tinycompressed.jpg should just be some really compressed image that will load in a lot faster and be so much smaller than your main image.

<img id='the-image' class='img-fluid' alt='alttext' src='tinycompressed.jpg' style='width: 100%; height: 100%;'>

Place this vanilla Javascript before the closing </body> tag:

window.addEventListener('load', function () {
    loadHighResImage(document.getElementById('the-image'), 'mainimage.jpg')
})

function loadHighResImage(elem, highResUrl) {
    let image = new Image()
    image.addEventListener('load', () => elem.src = highResUrl)
    image.src = highResUrl
}

mainimage.jpg is what you will want to be replacing with your main image file name.

Thats it, this is what the execution looks like

The fuzzy, smaller file loads first and then comes the main image. This beats having no image at all and then all of a sudden the image pops in.