You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在设置img的src属性前检查图片是否已完全加载?

How to Ensure Images Are Fully Loaded Before Setting the 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 preloader image runs in the background—users won't see it until it's ready to be assigned to your visible element.
  • The onload event guarantees we only set the src after the image is 100% loaded and stored in the browser's cache.
  • The onerror handler gives you a safety net for broken image links, so your page stays polished.
  • We fixed the class selector to properly target .loadlater elements.

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 09:04:37