Detecting Image Load Completion with the onload Event and Understanding Image Request Timing
This article explains how to use the onload event to determine when an Img element has finished loading, provides JavaScript examples for sequential loading, discusses why onreadystatechange is unsuitable, and explores when browsers issue image requests and how CSS affects them.
Today I encountered an interview question about image loading and decided to record the solution: knowing when an image finishes loading solves the problem.
Using the onload event to determine when an Img tag has loaded
The logic creates a new Image instance, sets its src , and appends the image to a parent element inside the onload handler. After appending, the first URL is removed from the array and the function recurses until the array is empty.
const imgArrs = [...]; // image URLs
const content = document.getElementById('content');
const loadImg = () => {
if (!imgArrs.length) return;
const img = new Image(); // create Image object
img.src = imgArrs[0];
img.setAttribute('class', 'img-item');
img.onload = () => {
content.appendChild(img);
imgArrs.shift();
loadImg();
};
img.onerror = () => {
// handle error
};
};
loadImg();Adding a setTimeout (e.g., 500 ms) makes the loading effect more noticeable.
Although some sources suggest using onreadystatechange , this property only exists on XMLHttpRequest and Document objects, not on Image elements, so it should be avoided for other elements.
Extended knowledge
When does an img tag send a request for its resource?
During HTML parsing, as soon as the browser encounters an img tag with a src , it immediately starts a request.
When an img element is created dynamically and its src is set, the request is sent even if the element has not yet been added to the DOM.
// Example 1:
const img = new Image();
img.src = 'http://xxxx.com/x/y/z/ccc.png';The code above triggers a network request as soon as it runs.
Another example creates a div and inserts an img string into its innerHTML. Even though the div is not yet attached to the document, the browser still requests the image.
// Example 2:
const img = `
`;
const dom = document.createElement('div');
dom.innerHTML = img;Therefore, the request occurs.
Can CSS prevent an image request?
Setting display:none or visibility:hidden on an img does not stop the request.
Using a background image on an element that does not exist in the DOM prevents the request; the request is only made when the element is present.
<img src="http://xxx.com/x/sdf.png" style="display: none;">
<img src="http://xxx.com/x/sdf.png" style="visibility: hidden;"> <!DOCTYPE html>
<html lang='en'>
<head>
<meta charset='UTF-8'>
<title></title>
<style>
.test {
height: 200px;
background-image: url('http://example.com/image.png');
}
</style>
</head>
<body>
<div></div>
</body>
</html>If the element with class test does not exist in the DOM, the background image request is not sent; it is sent only when the element is present.
A complete page consists of js , html , and css . While the browser parses HTML first, the actual loading of resources occurs after the HTML document is loaded. img elements are part of the content and therefore start loading before CSS background images.
If any part of the article is inaccurate, readers are welcome to provide corrections.
Rare Earth Juejin Tech Community
Juejin, a tech community that helps developers grow.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.