Seth is currently live on Twitch! Go There Now?
November 3, 2019
Advice I Wish I Could Take For Myself
How To Delay Image Loading Until It's In View

So I had another idea with the image loading. This time, I wanted to make it so images don't load unless they are in view. This should help out page times a little bit and make a nice little fade in effect whenever you see new images. This also allows me to animate them in interesting ways on load. I'll explain the code as I write it.

  • <script>
  • /** change any data-src into a real image and fade in **/
  • //-> function for setting the destination css, css's transition time will take care of the animation
  • function setCSS(that){
  • that.css({
  • 'filter':'none',
  • 'margin-top':'0px',
  • 'opacity':'1'
  • });
  • }
  • //-> function for the image loading process
  • function loadImages(){
  • //-> select all elements that don't have data-ani = tru, which we'll define later so the function will stop interacting with the elements after it's done animating them in
  • $("img").not("[data-ani='tru']").each(function(){
  • var that = $(this); //-> we'll reference $(this) a million times, let's set it as a variable
  • //-> if the image's src info hasn't been moved to data-src, do it now
  • if(that.attr('src')&&!that.attr('data-src')){
  • that.attr('data-src',that.attr('src')).attr('src','');
  • }
  • //-> if element's top offset is more than scroll top + window height, it should load in
  • if(that.offset().top<($(window).scrollTop()+$(window).height())&&!that.attr('src')){
  • //-> push data-src back to src, add 'tru' to arbitrary 'data-ani', load image in, use setCSS function
  • that.attr('src',that.attr('data-src')).attr('data-ani','tru').on('load',setCSS(that));
  • }
  • });
  • }
  • loadImages();
  • $(window).bind('scroll resize',loadImages);
  • </script>

So as you see, the image src url will be moved to a random data attribute (data-src) which doesn't let the image load. Then, when it's in view of the browser, it will be placed back to src, and we attach an on load event that fades the image from zero opacity to full opacity when the image itself is loaded. This way, we only load the image if and when we need to. If the viewer doesn't scroll down the page, then there's no need to load the image.

 Profile Picture
Comment