【问题标题】:HTTP request delayed in Chrome if dev tools not open如果开发工具未打开,Chrome 中的 HTTP 请求会延迟
【发布时间】:2018-02-28 02:28:14
【问题描述】:
我正在开发一个应用程序中的webpage,该应用程序使用一些 JavaScript 从API endpoint 获取数据。
在 Safari 和 FireFox 中,我可以连续多次请求页面,并及时获取并显示数据。相比之下,在 Chrome 中,只有在开发工具打开或我的缓存已清除(尽管我没有在开发工具中禁用缓存)时,才会立即获取并显示数据。
如果开发工具未打开或 Chrome 已缓存页面,则重新加载页面大约需要 10 秒才能发出请求并显示数据。
有谁知道可能导致这种行为的原因是什么? Full app source.
【问题讨论】:
标签:
google-chrome
google-chrome-devtools
【解决方案1】:
有问题的 API 请求使用 isomorphic-fetch 发出请求。我用旧式 AJAX 请求替换了 isomorphic-fetch 代码,现在请求按预期立即触发。
之前:
import fetch from 'isomorphic-fetch';
export const fetchTreeData = () => {
return function(dispatch) {
return fetch(config.endpoint + 'tree')
.then(response => response.json()
.then(json => ({
status: response.status,
json
})))
.then(({ status, json }) => {
if (status >= 400) dispatch(treeRequestFailed())
else dispatch(receiveTreeData(json))
}, err => { dispatch(treeRequestFailed(err)) })
}
}
之后:
export const fetchTreeData = () => {
return function(dispatch) {
get(config.endpoint + 'tree',
(data) => dispatch(receiveTreeData(JSON.parse(data))),
(e) => console.log(e))
}
}
const get = (url, success, err, progress) => {
const xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = () => {
if (xmlhttp.readyState == XMLHttpRequest.DONE) {
if (xmlhttp.status === 200) {
if (success) success(xmlhttp.responseText);
} else {
if (err) err(xmlhttp);
}
};
};
xmlhttp.onprogress = (e) => {if (progress) progress(e)};
xmlhttp.open('GET', url, true);
xmlhttp.send();
};