简体   繁体   中英

Show static image but swap with animated GIF once GIF if fully loaded

I'm building a site that is heavy with many large (800KB) animated GIFs. I also have the first frame of each GIF that I'm planning on showing initially and then later swap it to the animated GIF's once they have been loaded. That way the site will still look fine initially.

I'm currently storing the GIF url in the image tag as "data-gif='blah.gif'". I can then iterate through these with jQuery to get the GIF URLs.

Now I'm not sure how to load these in the background and get an event for when they are loaded.

You want an "image preloader". Here's an example to get you started, but I'd recommend searching for a library that has some more thought around handling edge cases.

 function preload(i, img) { console.log(img); var $img, url, $pre; $img = $(img); // incoming <img/> must have a 'data-gif' attribute if (! $img || ! $img.data('gif')) { return; } url = $img.data('gif'); $pre = $('<img />'); // Set up handler to replace original images's 'src' attribute // with the data-gif URL once the replacement is loaded $pre.on('load', function() { $img.attr('src', url); }); $pre.attr('src', url); } $('#images img').each(preload); 
 #images img { width: 320px; } #images { list-style: none; } #images li { margin-bottom: 2rem; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <h1>Image preloader test</h1> <ul id="images"> <li><img src="//placehold.it/960x540/99eeee" data-gif="http://static1.1.sqspcdn.com/static/f/1376538/22414391/1365600694390/typing.gif?token=v5utJCt1OsYJZ%2BIzFfWubDICtZI%3D" /></li> <li><img src="//placehold.it/960x540/ee99ee" data-gif="http://static1.1.sqspcdn.com/static/f/1376538/22414389/1365600692520/reading.gif?token=v5utJCt1OsYJZ%2BIzFfWubDICtZI%3D" /></li> <li><img src="//placehold.it/960x540/eeee99" data-gif="http://static1.1.sqspcdn.com/static/f/1376538/22414392/1365600694820/wireframe.gif?token=v5utJCt1OsYJZ%2BIzFfWubDICtZI%3D" /></li> <li>Broken link: never swaps:<br/><img src="//placehold.it/960x540/999999" data-gif="http://example.com/asfazsdasfd.gif" /></li> </ul> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM