Created
August 20, 2021 13:11
-
-
Save dsheiko/734e63f63cead274297c25e0bba7b27c to your computer and use it in GitHub Desktop.
Function runs callback when all the images in the document fully loaded
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* @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