每当DIV第一次可见时加载(延迟加载)Div

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

就像Jquery Image加载http://www.appelsiini.net/projects/lazyload一样 ,它只对图像有效。

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

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

我将使用JSON或PageMethods下载内容。 但我想要执行加载内容的函数的代码。

因此,我们是否能够以某种方式找到这个div只能向下滚动才能看到。

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

任何帮助表示赞赏。

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

 $(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 } } }); }); 

正确的解决方案 ,从这里考虑从底部滚动。

我正在寻找这个只在广告应该可见时从我的openX服务器加载广告。 我正在使用加载在div中的openX的iFrame版本。 这里的答案让我开始解决这个问题,但是发布的解决方案有点过于简单了。 首先,当页面未从顶部加载时(如果用户通过单击“返回”进入页面),则不会加载任何div。 所以你需要这样的东西:

 $(document).ready(function(){ $(window).scroll(lazyload); lazyload(); }); 

此外,您需要知道什么定义了可见的div。 这可以是完全可见或部分可见的div。 如果对象的底部大于或等于窗口的顶部并且对象的顶部小于或等于窗口的底部,则它应该是可见的(或者在这种情况下:加载)。 你的函数lazyload()可能如下所示:

 function lazyload(){ var wt = $(window).scrollTop(); //* top of the window var wb = wt + $(window).height(); //* bottom of the window $(".ads").each(function(){ var ot = $(this).offset().top; //* top of object (ie advertising div) var ob = ot + $(this).height(); //* bottom of object if(!$(this).attr("loaded") && wt<=ob && wb >= ot){ $(this).html("here goes the iframe definition"); $(this).attr("loaded",true); } }); } 

我在所有主流浏览器甚至是我的iPhone上都测试了这个。 它就像一个魅力!

你可以考虑方式点库:)

http://imakewebthings.com/waypoints/api/waypoint/

它的用例和api在上面的链接中定义

压缩时为9 kb。 在3g / 4g上加载页面时,它会额外增加-100 ms- 50ms timelag

编辑: – 它可以单独使用,它也支持所有主要框架。

这是一个解决方案,当它们在500px视图范围内时,延迟加载图像。 它可以适用于加载其他类型的内容。 图像本身有一个属性data-lazy="http://..."其中包含图像url,然后我们只为src属性放置一个虚拟透明图像。

 var pixelLoadOffset = 500; var debouncedScroll = debounce(function () { var els = app.getSelector(el, 'img[data-lazy]'); if (!els.length) { $(window).unbind('scroll', debouncedScroll); return; } var wt = $(window).scrollTop(); //* top of the window var wb = wt + $(window).height(); //* bottom of the window els.each(function () { var $this = $(this); var ot = $this.offset().top; //* top of object var ob = ot + $this.height(); //* bottom of object if (wt <= ob + pixelLoadOffset && wb >= ot - pixelLoadOffset) { $this.attr('src', $this.attr('data-lazy')).removeAttr('data-lazy'); } }); }, 100); $(window).bind('scroll', debouncedScroll); 

我正在使用的去抖function如下:

 function debounce(func, wait, immediate) { var timeout; return function () { var context = this, args = arguments; clearTimeout(timeout); timeout = setTimeout(function () { timeout = null; if (!immediate) func.apply(context, args); }, wait); if (immediate && !timeout) func.apply(context, args); }; } 

你需要记住,这在iOS上不是很有效,因为滚动事件直到用户完成滚动之后才会触发,到那时他们已经看过空白内容。