How do I abort image

前端 未结 7 2086
盖世英雄少女心
盖世英雄少女心 2020-11-29 01:23

I have a very long page that dynamically loads images as users scroll through.

However, if a user quickly scrolls away from a certain part of the page, I don\'t want

7条回答
  •  佛祖请我去吃肉
    2020-11-29 01:55

    You can load your images using ajax calls, and in case that the uses scrolls-out, you can abort the calls.
    In jQuery pseudo-code it would be something like that (forgive me mistakes in syntax, it is just an example):

    1) tag images that you want to load

    $(".image").each( function(){
        if ( is_in_visible_area(this) ) { // check [1] for example
            $(this).addClass("load_me");
        } else {
            $(this).addClass("dont_load");
        }
    });
    

    2) load images

    ajax_requests = {};
    
    $(".image.load_me").each( function(){
        // load image
        var a = $.ajax({
            url: 'give_me_photos.php',
            data: {img: photo_id},
            success: function(html){
                photo_by_id(photo_id), img.append(html);
            }
        });
        ajax_requests[photo_id] = a;
    
    });
    

    3) cancel loading those out of the screen

    for( id in ajax_requests ) {
        if ( ! is_in_visible_area(id) ) {
            ajax_requests[id].abort();
        }
    }
    

    Of course, add also some checking if the image is already loaded (e.g. class "loaded")

    [1]. Check if element is visible after scrolling

    [2]. Abort Ajax requests using jQuery

提交回复
热议问题