在div中jquery延迟加载内容

时间:2014-01-19 16:18:12

标签: jquery html5 scroll

我想在div中加载内容。我有很多jquery scoll插件但是它们都用于整页加载。我想在滚动到达div底部时加载现有div中的内容。任何人都可以帮助我吗?

3 个答案:

答案 0 :(得分:5)

你可以使用JQuery和Ajax做这样的事情:

var loading = false;//to prevent duplicate

function loadNewContent(){       
    $.ajax({
        type:'GET',
        url: url_to_new_content    
        success:function(data){
            if(data != ""){
                loading = false;
                $("#div-to-update").html(data);
            }
        }
    });
}

//scroll DIV's Bottom 
$('#div-to-update').on('scroll', function() {
    if($(this).scrollTop() + $(this).innerHeight() >= $(this)[0].scrollHeight) {
        if(!loading){
            loading = true;
            loadNewContent();//call function to load content when scroll reachs DIV bottom                
        }   
    }
})


//scroll to PAGE's bottom
var winTop = $(window).scrollTop();
var docHeight = $(document).height();
var winHeight = $(window).height();
if  ((winTop / (docHeight - winHeight)) > 0.95) {       
    if(!loading){
        loading = true;
        loadNewContent();//call function to load content when scroll reachs PAGE bottom                
    }       
}

FIDDLE

答案 1 :(得分:3)

你可以使用JQuery和lazyload plugin来做这样的事情。

你的div:

<div data-src="transparent.png" url="http://stackoverflow.com"></div>

使用beforeLoad回调:

jQuery(function($) {
    $("div[url]").lazy({
        beforeLoad: function (element) {
            element.load(element.attr("url"));
        }
    });
});

答案 2 :(得分:0)

我知道这是一个古老的主题,但只是为了完整:如前所述,你可以使用jQuery.Lazy。但我不会这样做的方式。 :)已经有一个插件可以通过AJAX加载<div>内容。

将插件添加到您的页面:您还需要jQuery或Zepto

<script type="text/javascript" src="//cdn.jsdelivr.net/jquery.lazy/1.7.1/jquery.lazy.min.js"></script>
<script type="text/javascript" src="//cdn.jsdelivr.net/jquery.lazy/1.7.1/plugins/jquery.lazy.ajax.min.js"></script>

准备你的div:注意data-loaderdata-src属性

<div data-loader="ajax" data-src="ajax.html"></div>

并开始使用Lazy:

$(function() {
    $("div[data-src]").Lazy();
});

就是这样!只要用户通过滚动到达data-src,就会加载<div>中给出的内容。更多内容here