每当DIV第一次可见时加载(延迟加载)Div [英] Load (Lazy Loading) a Div whenever the DIV gets visible for the first time

查看:392
本文介绍了每当DIV第一次可见时加载(延迟加载)Div的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想为我的网站内容启用延迟加载。

I want to enable a lazy loading for the contents of my website.

就像Jquery Image加载 http://www.appelsiini.net/projects/lazyload 仅对图片有效。

Just like Jquery Image loading http://www.appelsiini.net/projects/lazyload that is valid only for images.

我想为内容(DIV)做这件事。

I want to do it for the content (DIV's).

假设我们有一个长页面然后我想下载div,因为它们变得可见。

Suppose we have a long page then i want to download the div as they becomes visible.

我将使用JSON或PageMethods下载内容。但我希望代码能够执行加载内容的功能。

I will download the content using JSON or PageMethods. But i want the code that will execute the function for loading contents.

因此,我们是否能够以某种方式找到div只能向下滚动显示。

So whether we can somehow find this that div is visible only scrolling down.

意味着我需要使用一些滚动事件,但不知道如何。

Means i need to use some scroll events but dont know how.

感谢任何帮助。

推荐答案

下面的代码不包括用户从底部向上滚动的情况(请参阅下面的patrick评论)。此外,它允许多个事件执行,因为有几个并发的 onscroll 事件(在大多数浏览器中,大多数情况下你都不会看到这个)。

The code below does not cover cases where the user scrolls up from the bottom (read patrick's comment below). Also, it allows multiple event executions because of several concurrent onscroll events (in most browsers you won't see this, most of the time).

$(document).ready(function(){
    $(window).scroll(function() {
        //check if your div is visible to user
        // CODE ONLY CHECKS VISIBILITY FROM TOP OF THE PAGE
        if ($(window).scrollTop() + $(window).height() >= $('#your_element').offset().top) {
            if(!$('#your_element').attr('loaded')) {
                //not in ajax.success due to multiple sroll events
                $('#your_element').attr('loaded', true);

                //ajax goes here
                //in theory, this code still may be called several times
            }
        }
    });
});

正确解决方案,考虑从底部滚动

这篇关于每当DIV第一次可见时加载(延迟加载)Div的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆