Question

I'm using a function below to preload images on my ajax page. My page contains image galleries. But I need to stop preloading of current gallery when I click another gallery link. Any help? Thanks...

It's solved... Here's working code with an example...

<html>
<head>
<script type="text/javascript">

(function($) {
    imgList = [];
    $.extend({
        preload: function(imgArr, option) {
            var setting = $.extend({
            init: function(loaded, total) {},
            loaded: function(img, loaded, total) {},
            loaded_all: function(loaded, total) {},
            cancel: function() {}
        }, option);
            setting.cancel(imgList);
            var total = imgArr.length;
            var loaded = 0;
            setting.init(0, total);
            for(var i in imgArr) {
                imgList.push($("<img />")
                .attr("src", imgArr[i])
                .load(function() {
                    var loadedImg=$("img[src='"+$(this).attr("src")+"']");
                    if(loadedImg.attr("width")==undefined){
                        $("img[src='"+$(this).attr("src")+"']").attr({
                          width: this.width,
                          height: this.height
                        });
                    };
                    loaded++;
                    setting.loaded(this, loaded, total);
                    if(loaded == total) {
                        setting.loaded_all(loaded, total);
                        imgList = [];
                    };
                })
            );
        }
        }
    });
})(jQuery);    

function preload(arr,preloaderFunc,preloaderCompleteFunc){
    $.preload(arr, {
        init: function(loaded, total) {
            var percent=(100/total)*loaded;
            eval(preloaderFunc+"("+percent+")");
        },
        loaded: function(img, loaded, total) {
            var percent=(100/total)*loaded;
            eval(preloaderFunc+"("+percent+")");
        },
        loaded_all: function(loaded, total) {
           eval(preloaderCompleteFunc+"()")
        },
        cancel: function(imgList) {
            if(imgList.length>0){ 
                for(var i in imgList) {
                    console.log("remove:"+imgList[i])
                       imgList[i].unbind("load").remove();
                }
                imgList  = [];
            };
        }
    }); 
};

function preloader(percent){
   $(".loaderBar").stop().animate({ "width" : percent+"%" }, 500)
};

function initPreloadImgs(){
    if($('.preloadImgs').length != 0) {
       $('.preloadImgs').not(".preloadImgs-ok").each(function(index) {
            $(this).addClass("preloadImgs-ok");
            var preloaderFunc=hasClassVal($(this),"preloaderFunc:");
            var preloaderCompleteFunc=hasClassVal($(this),"preloaderCompleteFunc:");
            clearClass($(this),"preloaderFunc:");
            clearClass($(this),"preloaderCompleteFunc:");
            var preloadThem=[];
            $('.preloadImgs').find("img").each(function(){
                preloadThem.push($(this).attr("src"));
            });
            if(preloadThem.length==0){
                eval(preloaderCompleteFunc+"()");
            }else{
                preload(preloadThem,preloaderFunc,preloaderCompleteFunc);
            };
       });
    };
};

function preloaded(){
   $(".main").fadeIn(1000);
};

function hasClassVal(obj,val){
     var classes=$(obj).attr("class")!=undefined?$(obj).attr("class").split(" "):"";
     var valLength=val.length;
     var getVal=""
     for(var i in classes){ 
         var optz=classes[i];
         if(optz.length>valLength){        
           if(optz.substr(0,valLength) == val){
               getVal = optz.substr(valLength);
               break;
           };
         };
     };
     return getVal;
};

</script>
</head>
<body>
   <div class="loader"><div class="loaderBar"></div></div>
   <div class="main preloadImgs preloaderFunc:preloader preloaderCompleteFunc:preloaded" style="display:none;">
      <img src="assets/001.jpg"/>
      <img src="assets/002.jpg"/>
      <img src="assets/003.jpg"/>
   </div>
</body>
</html>
Was it helpful?

Solution

All you can do is free the image references you have in place. It will be up to the browser's internal implementation whether it drops the in-flight image requests or not. Clearing the event handlers will at least stop you from processing the images as they load. You can clear all the references by adding a cancel() method to your object like this:

cancel: function() {
    for (var i = 0; i < imgList.length; i++) {
        // clean up any jQuery data and event handlers associated with this object
        imgList[i].remove();
    }
    // clear out the imgList so all former array elements can be garbage collected
    imgList = [];
}

OTHER TIPS

If you put the loader in a class, you can create a loaded when a link is clicked. Any previous loader can get a property that tells it to stop loading.

Something like this:

function Loader(gallery)
{
  this.terminated = false;

  this.load = function()
  {
    // Loading code.
    for (loop condition)
    {
      // break if this.terminated becomes true.
    }
  }
}

var loader = null;
function preloadGallery(gallery)
{
  // Tell the previous one to stop.
  if (loader !== null)
    loader.terminated = true;
  // Start the new one.
  loader = new Loader(gallery);
}

Btw, it seems to me you're using a different technique than usual to preload the images. Take a look at this page.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top