滚动后再次停止加载iframe?

时间:2017-09-30 03:14:12

标签: javascript iframe

我有一个带iframe的页面...目前我使用此代码加载iframe onscroll ....

使用Javascript:

function lazyLoad() {
    for (var e = document.getElementsByClassName("lazy"), t = 0; t < e.length; t++) isInViewport(e[t]) && (e[t].src = e[t].getAttribute("data-src"))
      }
function isInViewport(e) {
    var t = e.getBoundingClientRect();
    return t.bottom >= 0 && t.right >= 0 && t.top <= (window.innerHeight || document.documentElement.clientHeight) && t.left <= (window.innerWidth || document.documentElement.clientWidth)
}
function registerListener(e, t) {
    window.addEventListener ? window.addEventListener(e, t) : window.attachEvent("on" + e, t)
}
registerListener("load", lazyLoad), registerListener("scroll", lazyLoad);

HTML:

<iframe data-src='http://some-link.com' src='' class='lazy'/>

但是当我再次滚动时,即使只是稍微滚动,iframe也会重新加载。我可以帮助我在第二次滚动后再次加载iframe吗?谢谢!

DEMO:http://design-jarwo.blogspot.co.id/我将在我的博客www.kodejarwo.com

上使用它

1 个答案:

答案 0 :(得分:0)

您必须在触发后删除滚动事件侦听器:

function onScroll () {
    if (lazyLoad()) {
        window.removeEventListener('scroll', onScroll);
    }
}
function onLoad () {
    lazyLoad();
}
function lazyLoad() {
    var loaded = false;
    for (var e = document.getElementsByClassName("lazy"), t = 0; t < e.length; t++) {
        isInViewport(e[t]) && (e[t].src = e[t].getAttribute("data-src"));
        loaded = true;
    }
    return loaded;
}
function isInViewport(e) {
    var t = e.getBoundingClientRect();
    return t.bottom >= 0 && t.right >= 0 && t.top <= (window.innerHeight || document.documentElement.clientHeight) && t.left <= (window.innerWidth || document.documentElement.clientWidth)
}
function registerListener(e, t) {
    window.addEventListener ? window.addEventListener(e, t) : window.attachEvent("on" + e, t)
}
registerListener("load", onLoad), registerListener("scroll", onScroll);