Skip to content

Instantly share code, notes, and snippets.

@dsheiko
Created August 20, 2021 13:11
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 dsheiko/734e63f63cead274297c25e0bba7b27c to your computer and use it in GitHub Desktop.
Save dsheiko/734e63f63cead274297c25e0bba7b27c to your computer and use it in GitHub Desktop.
Function runs callback when all the images in the document fully loaded
/**
* @returns Image[]
*/
function getIncompleteImages() {
return Array.from( document.querySelectorAll( "img" ) )
.filter( img => !img.complete || img.naturalWidth === 0 );
}
/**
* Execute the given callback when all the images in the document loaded
* We call this function when markup with images is rendered but images are still loading
* @param {Function} cb
*/
export default function( cb ) {
let imagesLoaded = 0;
const images = getIncompleteImages(),
imagesCount = images.length,
onLoad = () => {
imagesLoaded++;
if ( imagesLoaded >= imagesCount ) {
return cb();
}
};
if ( !imagesCount ) {
return cb();
}
images.forEach( img => {
img.addEventListener( "load", onLoad );
img.addEventListener( "error", onLoad );
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment