Skip to content

Instantly share code, notes, and snippets.

@dazulu
Last active March 21, 2018 14:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dazulu/27fbbfb21be3b0323f3e83d127461b45 to your computer and use it in GitHub Desktop.
Save dazulu/27fbbfb21be3b0323f3e83d127461b45 to your computer and use it in GitHub Desktop.
Lazy Person's Lazy Image Lazyloader

Lazy Person's Lazy Image Lazyloader

Though you could probably do it EVEN MORE lazily if you wanted #justsaying #doesntreallymatter.

I mashed this in here from a Vue component where I had a little bit more going on with props etc. but the same end result. If I open up the devtools Network tab I can see the high resolution images loading in after the rest of the page. Big perf wins!

If you want a challenge, it wouldn't be too much of a stretch to extend this to achieve something like what Medium does with the blurred image fading to the highres image. I haven't done it but it would be more or less along the lines of adding another image element, a wrapping container, and some sexy CSS.

In HTML...

<!-- Let the page render an image with a low res version (read: tiny file size). -->
<img class="my-image" src="lowResolution.jpg" />

Then in JS...

// Get the rendered on-screen image element.
const pageElement = document.querySelector('.my-image') 

// Link to the high resolution image file.
const highResFile = 'highResolution.jpg'

// Create an empty image to use to load the high res image file.
const imageLoader = new Image()

// Attach an 'onload' event listener to it, which will switch the 'src'
// of our on-screen image to the high res version.
imageLoader.onload = () => {
  pageElement.src = highResFile
  imageLoader = null
}

// Load the high res image in our JS created image loader.
// It will then trigger the above 'onload' function
imageLoader.src = highResFile
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment