JS postMessage用于调整父级iframe scrollHeight的性能问题



我有一个文件浏览器应用程序,我想集成到主网站的iframe中。为了根据内容调整iframte的滚动高度,我使用以下代码:

iframecontent:

    window.top.postMessage({ height: document.body.scrollHeight }, "*");

主站点html:

<iframe id="iframe1" src="https://mysubfilebrowser.com"  frameborder="0" scrolling="no" width="100%" height="10000">
    Your browser doesn't support iframes
</iframe>
<script>
    let iframe = document.getElementById("iframe1");
    window.addEventListener('message', function(e) {
        let message = e.data;
        iframe.style.height = message.height + 'px';
    } , false);
</script>

这是应该的,但我在性能方面有问题。如果我在文件/文件夹树中单击以快速发送,post message事件似乎被触发得太多了,以至于iframe突然没有显示正确的内容,甚至没有显示空白区域。

有什么提示我能做些什么来解决这个问题吗?

提前感谢!

致以最良好的问候Mini25

这听起来像是一个"单个";更改会使该调用运行多次(scrollresize事件可以是这样的(。为了处理这个问题,你可以";去跳动";您对postMessage的调用,因此当它在短时间内获得大量触发器时,它只进行一次调用。

这很简单:不要马上打电话,等待10、50或100毫秒后再打,如果你有另一个触发器,请重置延迟。这意味着在事情稳定下来之前,你不会真正去做。

这里有一个简单的即席版本,只针对该代码,但对";去跳动";将为函数打开各种通用的去抖动包装器:

let updateWindowDebounceTimer = 0;
function updateWindow() {
    // If there's a pending previous call, cancel it
    clearTimeout(updateWindowDebounceTimer);
    // Schedule a call for 10ms from now
    updateWindowDebounceTimer = setTimeout(sendUpdate, 100);
}
function sendUpdate() {
    updateWindowDebounceTimer = 0;
    window.top.postMessage({ height: document.body.scrollHeight }, "*");
}

然后在当前使用window.top.postMessage(/*...*/)的位置使用updateWindow();

下面是一个使用scroll事件而没有去抖动的例子(注意滚动时计数器上升的速度(:

function updateWindow() {
    /*
    window.top.postMessage({ height: document.body.scrollHeight }, "*");
    */
    const display = document.getElementById("counter");
    display.textContent = String(parseInt(display.textContent, 10) + 1);
}
window.addEventListener("scroll", updateWindow);
body {
    padding-top: 0;
    margin-top: 0;
}
#counter {
    position: sticky;
    top: 0;
}
.tall {
    margin-top: 1em;
    height: 10000px;
}
<div id="counter">0</div>
<div class="tall">Scroll over this div</div>

下面是一个带有去抖动的示例(注意计数器上升的速度有多慢,表示更新调用更少(:

let updateWindowDebounceTimer = 0;
function updateWindow() {
    // If there's a pending previous call, cancel it
    clearTimeout(updateWindowDebounceTimer);
    // Schedule a call for 10ms from now
    updateWindowDebounceTimer = setTimeout(sendUpdate, 50);
}
function sendUpdate() {
    updateWindowDebounceTimer = 0;
    /*
    window.top.postMessage({ height: document.body.scrollHeight }, "*");
    */
    const display = document.getElementById("counter");
    display.textContent = String(parseInt(display.textContent, 10) + 1);
}
window.addEventListener("scroll", updateWindow);
body {
    padding-top: 0;
    margin-top: 0;
}
#counter {
    position: sticky;
    top: 0;
}
.tall {
    margin-top: 1em;
    height: 10000px;
}
<div id="counter">0</div>
<div class="tall">Scroll over this div</div>

这是一个特别的版本,但在网上搜索";去跳动";将为函数打开各种通用的去抖动包装器。

最新更新