2017-08-08 105 views
0

目前我玩弄异步页面加载和我已经达到了当接收到响应以下实现:设置的持续时间将被延迟xhr.onload

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

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

我给自己定的延迟250 ms以确保在更换和淡入新内容之前,先前的内容块有机会完成其淡出动画。这样做的问题是,除非我立即得到xhr响应(当然这不会在现实世界中发生),否则内容加载时总会有延迟。

什么是允许的页面来呈现新的内容之前等待至少250ms的最好的办法 - 那就是:

  • 如果需要100毫秒获得一个XHR响应,还需要之前要等待150毫秒替换内容
  • 如果需要1秒钟才能获得xhr响应,则旧内容块淡出已经很久,因此已经完成,因此立即加载新内容。

回答

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]因为动画尚未完成。

只有在丢失的情况下运行内容才会最终更新。

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.