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…

1 year ago

Merrimu Reservoir drone images

Merrimu Reservoir from drone. Click images to view larger.

1 year ago

FTP getting array of file details such as size using PHP

Using FTP and PHP to get an array of file details such as size and…

2 years ago

Creating Laravel form requests

Creating and using Laravel form requests to create cleaner code, separation and reusability for your…

2 years ago

Improving the default Laravel login and register views

Improving the default Laravel login and register views in such a simple manner but making…

2 years ago

Laravel validation for checking if value exists in the database

Laravel validation for checking if a field value exists in the database. The validation rule…

2 years ago