Categories: Development

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.

Share

Recent Posts

Kennington reservoir drained drone images

A drained and empty Kennington reservoir images from a drone in early July 2024. The…

2 years ago

Merrimu Reservoir drone images

Merrimu Reservoir from drone. Click images to view larger.

2 years ago

Early September spring shots

Some early September spring shots from a bushwalk, It is still too early for wildflowers.

3 years ago

Cloning an NVMe to SK Hynix Platinum P41 NVMe

I recently needed to clone over a smaller NVMe to a 2TB SK Hynix Platinum…

3 years ago

Using Laravel’s deleteDirectory to delete folders and their contents

If you ever needed a simple solution in Laravel to delete an entire directory and…

3 years ago

How to allow only 1 user to register in a Laravel application

How to enforce only one user to register or be registered in a Laravel web…

3 years ago