我有一个包含iframe的页面,iframe只有在视口中才需要加载的元素很少。
但是iframe不可滚动,只有母版页有滚动。我已经编写了以下函数,但如果与母版页一起使用则无效。
function isVisible(a) {
var b1 = a.getBoundingClientRect(),
b={},
c = window.innerWidth || doc.documentElement.clientWidth,
d = window.innerHeight || doc.documentElement.clientHeight,
e = function(a, b) {
return document.elementFromPoint(a, b)
};
if(window.frameElement){
var w = window.frameElement.getBoundingClientRect();
// d = window.innerHeight || doc.documentElement.clientHeight;
for( var i in b1){
b[i]=Math.abs(b1[i])+Math.abs(w[i])
}
}else{
b=b1;
}
return !(b.right < 0 || b.bottom < 0 || b.left > c || b.top > d) && (a.contains(e(b.left, b.top)) || a.contains(e(b.right, b.top)) || a.contains(e(b.right, b.bottom)) || a.contains(e(b.left, b.bottom)))
}
请提前表明前进的方法。
答案 0 :(得分:0)
这将推迟加载iframe
内容,直到滚动到视图中。
var $iframe = $("#iframe");
$(window).on("scroll", function() {
// you should probably throttle or debounce this method; I didn't
if (isScrolledIntoView($iframe[0])) {
// assumes same origin for iframe
// if iframe has window object and function "viewportUpdate" call function
var iframeWindow = $iframe[0].contentWindow;
if (iframeWindow && iframeWindow.viewportUpdate)
{
var docViewTop = $(window).scrollTop();
var docViewBottom = docViewTop + $(window).height();
iframeWindow.viewportUpdate(docViewTop, docViewBottom);
}
}
});
// from http://stackoverflow.com/questions/487073/check-if-element-is-visible-after-scrolling
function isScrolledIntoView(elem) {
var docViewTop = $(window).scrollTop();
var docViewBottom = docViewTop + $(window).height();
var elemTop = $(elem).offset().top;
var elemBottom = elemTop + $(elem).height();
return ((elemBottom <= docViewBottom) && (elemTop >= docViewTop));
}
iframe
内容使用此方法来实现您的魔力:
function viewportUpdate(docViewTop, docViewBottom)
{
// do your magic here.. whatever that is
// for example, loop over each "img" element and log to console if in view
$("img").each(function()
{
var elemTop = $(elem).offset().top;
var elemBottom = elemTop + $(elem).height();
var elementIsInView = (elemBottom <= docViewBottom) && (elemTop >= docViewTop);
if (elementIsInView)
{
console.log("iframe img element is in view");
}
});
}