Moo*_*ons 26 javascript jquery
我想为我的网站内容启用延迟加载.
就像Jquery Image加载http://www.appelsiini.net/projects/lazyload一样,它只对图像有效.
我想为内容(DIV)做这件事.
假设我们有一个长页面然后我想下载div,因为它们变得可见.
我将使用JSON或PageMethods下载内容.但我想要执行加载内容的函数的代码.
因此,无论我们是否能够以某种方式找到div,只有向下滚动才能看到div.
意味着我需要使用一些滚动事件,但不知道如何.
任何帮助表示赞赏.
pat*_*ick 30
我正在寻找这个只在广告应该可见时从我的openX服务器加载广告.我正在使用加载在div中的openX的iFrame版本.这里的答案让我开始解决这个问题,但是发布的解决方案有点过于简单了.首先,当页面未从顶部加载时(如果用户通过单击"返回"进入页面),则不会加载任何div.所以你需要这样的东西:
$(document).ready(function(){
$(window).scroll(lazyload);
lazyload();
});
Run Code Online (Sandbox Code Playgroud)
此外,您需要知道什么定义了可见的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 (i.e. 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);
}
});
}
Run Code Online (Sandbox Code Playgroud)
我在所有主流浏览器甚至是我的iPhone上测试了这个.它就像一个魅力!
Oro*_*102 21
下面的代码不包括用户从底部向上滚动的情况(请参阅下面的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
}
}
});
});
Run Code Online (Sandbox Code Playgroud)
正确的解决方案,从这里考虑从底部滚动.