设置xhr.onload的持续时间延迟

时间:2017-08-08 03:30:22

标签: javascript ajax xmlhttprequest

目前我正在使用异步页面加载,并且在收到响应时已达到以下实现:

xhr.onload = function( event ) {
    var res = event.target.responseXML;

    // Update page content
    setTimeout( function() {
        content.innerHTML = res.querySelector( '.content' ).innerHTML;
    }, 250 );
};

我设置了250毫秒的延迟,以确保之前的内容块有机会在替换和淡入新内容之前完成淡出动画。这个问题是加载内容时总会有延迟,除非我立即得到xhr响应(当然这在现实世界中不会发生)。

在允许页面呈现新内容之前,等待至少250毫秒的最佳方法是什么 - 即:

  • 如果需要100毫秒才能获得xhr响应,仍需要等待150毫秒才能更换内容
  • 如果获得xhr响应需要1秒钟,旧内容块淡出已经很久就完成了,因此立即加载新内容。

2 个答案:

答案 0 :(得分:1)

There can be two ways to achieve this:

1. Set the response of the xhr in a global variable and assign it after the fade out is completed.

2.You can run a loop inside the onload function and check if the content is faded out, if yes then load the new content in.

The fade out can be checked via any DOM property changes.

答案 1 :(得分:0)

更新

我现在有一个有效的解决方案,但它看起来并不优雅。

function fetchPage() {
    var xhr = new XMLHttpRequest();
    var hasFinishedAnimating = false;
    var res;

    xhr.open( 'GET', window.location.href, true );
    xhr.responseType = 'document';
    xhr.send();

    // [1]
    setTimeout( function() {
        hasFinishedAnimating = true;
        if ( res ) updateContent( res );
    }, 250 );

    // [2]
    xhr.onload = function( event ) {
        res = event.target.responseXML.querySelector( '.content' ).innerHTML;
        if ( hasFinishedAnimating ) updateContent( res );
    };
}

// Update page content
function updateContent( html ) {
    content.innerHTML = html;
}

所以这里发生的事情是有一场比赛正在进行。以下案例之一将首先完成:

  • [1]倒计时(淡出动画)将完成
  • [2]获取新内容

首先运行的情况总是会失败 - [1] 因为内容仍然被提取而 [2] 因为动画还没有完成。

只有当失败案例运行时,内容才会最终更新。

相关问题