CodexBloom - Programming Q&A Platform

jQuery .fadeIn() optimization guide on images loaded from a CDN with a delay

πŸ‘€ Views: 72 πŸ’¬ Answers: 1 πŸ“… Created: 2025-06-14
jquery fadein images cdn load JavaScript

I'm working with an scenario where I'm trying to fade in images that I load from a CDN. The images are initially hidden with CSS, and I'm using jQuery's `.fadeIn()` method to display them after they are fully loaded. However, sometimes the images do not fade in as expected, especially when there's a delay in loading from the CDN. Here’s a simplified version of my code: ```html <div class="image-container"> <img class="lazy-load" src="https://cdn.example.com/image.jpg" alt="Example Image" style="display:none;"> </div> ``` ```javascript $(document).ready(function() { $('.lazy-load').on('load', function() { $(this).fadeIn(1000); }).each(function() { // Check if the image is already loaded if (this.complete) { $(this).fadeIn(1000); } }); }); ``` I am checking if the image is loaded before calling `.fadeIn()`, but it sometimes fails to trigger when the image takes longer to load due to network conditions. I’ve tried using the `.load()` event, but it seems inconsistent. In the console, I sometimes see that the load event doesn't fire, leading to no fade-in effect. Is there a better approach or a workaround for ensuring that the fade-in effect always triggers reliably regardless of the loading time? I'm using jQuery version 3.6.0 and have tested it across different browsers.