如何在设置img的src属性前检查图片是否已完全加载?
src Attribute Got it, let's work through this. First, I spotted a small bug in your original code: you missed the dot in the class selector ($("loadlater") should be $(".loadlater"))—that would have stopped your code from targeting the images entirely.
Now, to answer your core question: if you want to make sure the image is fully loaded before assigning it to your .loadlater elements, the most reliable approach is to preload the image using a temporary Image object. This loads the image into the browser's cache first, so when you set it to your visible <img> tag, it displays instantly without loading lag.
Here's the revised code with preloading and error handling built in:
$(document).ready(function(){ $(".loadlater").each(function(index, element){ const $targetImg = $(element); const imagePath = $targetImg.attr("data-src"); // Create a hidden temporary image to handle preloading const preloader = new Image(); // Triggered once the image finishes loading successfully preloader.onload = function() { // Now that the image is fully cached, assign it to the visible img $targetImg.attr("src", imagePath); // Optional: Clean up the data-src attribute if you don't need it anymore $targetImg.removeAttr("data-src"); }; // Handle cases where the image fails to load (e.g., broken link) preloader.onerror = function() { console.error(`Failed to load image: ${imagePath}`); // Fallback to a placeholder image to avoid broken image icons $targetImg.attr("src", "path/to/your/placeholder-image.png"); }; // Start the preload process preloader.src = imagePath; }); });
Quick Breakdown:
- The temporary
preloaderimage runs in the background—users won't see it until it's ready to be assigned to your visible element. - The
onloadevent guarantees we only set thesrcafter the image is 100% loaded and stored in the browser's cache. - The
onerrorhandler gives you a safety net for broken image links, so your page stays polished. - We fixed the class selector to properly target
.loadlaterelements.
If you're trying to check if an image was already loaded (e.g., cached from a prior visit), this approach still works—if the image is already in cache, the onload event fires instantly, so there's no unnecessary delay.
内容的提问来源于stack exchange,提问作者Krip

