JavaScript waiting until an image is fully loaded before continuing script

前端 未结 3 1310
太阳男子
太阳男子 2021-01-17 09:56

I\'ve been looking around a lot of JavaScript answers but I haven\'t found one that really answers my problem yet. What I\'m trying to do is load an image, grab the pixel da

相关标签:
3条回答
  • 2021-01-17 10:31

    Maybe try this:

    http://jsfiddle.net/jnt9f/

    Setting onload handler before setting img src will make sure the onload event be fired even the image is cached

    var $imgs = $(),i=0;
    for (var img = 0; img < imageURLarray.length; img++) {
       $imgs = $imgs.add('<img/>');
    }
    
    var fctn = (function fctn(i){
        $imgs.eq(i).on('load',function(){
            //do some stuff
            //...
            fctn(++i);
        }).attr('src',imageURLarray[i]);    
    })(0);
    
    0 讨论(0)
  • 2021-01-17 10:53

    Actually...a lot of developers are pointing here to detect when images are done loading after a jQuery event..

    https://github.com/desandro/imagesloaded

    If you can determine when the event triggers your images to load (for example, adding an Id or class onto the page right before your images begin to load), then you should be able to blend that in with this plug-in on github.

    Good Luck!

    0 讨论(0)
  • 2021-01-17 10:54

    Maybe this will help:

    currentimage.onload = function(e){
        // code, run after image load
    }
    

    If it is necessary to wait for the image to load, the following code will load the next image (currentIndex is your "img" variable):

    var loadImages = function(imageURLarray, currentIndex){
        if (imageURLarray.length == 0 || imageURLarray.length == currentIndex) return false;
        if (typeof currentIndex == 'undefined'){
           currentIndex = 0;
        }
        // your top code
        currentimage.onload = function(e){
            // code, run after image load
            loadImages(imageURLArray, currentIndex++);
        }
    }
    

    Instead of a "for" loop, use for example this function:

    loadImages(imageURLarray);
    
    0 讨论(0)
提交回复
热议问题