How do I abort image load requests without using window.stop()

What you are trying to do is the wrong approach, as mentioned by nrabinowitz. You can’t just “cancel” the loading process of an image (setting the src attribute to an empty string is not a good idea). In fact, even if you could, doing so would only make things worst, as your server would continually send data that would get cancelled, increasing it’s load factor and slow it down. Also, consider this:

  1. if your user scroll frenetically up and down the page, he/she will expect some loading delays.
  2. having a timeout delay (ex: 200 ms) before starting to load a portion of the page is pretty acceptable, and how many times will one stop and jump after 200 ms interval on your page? Even it it happens, it comes back to point 1
  3. how big are your images? Even a slow server can serve about a few tens of 3Kb thunbnails per second. If your site has bigger images, consider using low and hi resolution images with some components like lightBox

Often, computer problems are simply design problems.

** EDIT **

Here’s an idea :

  1. your page should display DIV containers with the width and height of the expected image size (use CSS to style). Inside of each DIV, add an link. For example :

    <div class="img-wrapper thumbnail">
       <a href="http://www.domain.com/path/to/image">Loading...</a>
    </div>
    
  2. Add this Javascript (untested, the idea is self describing)

    $(function() {
    
    var imgStack;
    var loadTimeout;
    
    $(window).scroll(function() {
       imgStack = null;
       if (loadTimeout) clearTimeout(loadTimeout);
    
       loadTimeout = setTimeout(function() {
    
          // get all links visible in the view port
          // should be an array or jQuery object
          imgStack = ...
    
          loadNextImage();
       }, 200);                // 200 ms delay
    });
    
    function loadNextImage() {
       if (imgStack && imgStack.length) {
          var nextLink = $(imgStack.pop());   // get next image element
    
          $('<img />').attr('src', nextLink.attr('href'))
            .appendTo(nextLink.parent())
            .load(function() {
               loadNextImage();
            });
    
          // remove link from container (so we don't precess it twice)
          nextLink.remove();
       }
    };
    
    });
    

Leave a Comment