我注意到请求的文件大小会影响ajax调用的响应时间。因此,如果我发出3个不同大小的文件的ajax GET请求,它们可能以任何顺序到达。我想要做的是保证在将文件附加到DOM时的排序。
如何设置队列系统,以便在我触发A1-> A2-> A3时。我可以保证按顺序将它们称为A1-> A2-> A3。
例如,假设A2在A1之前到达。我希望行动等到A1的到达和加载。
一个想法是使用定时回调创建状态检查器
// pseudo-code
function check(ready, fund) {
// check ready some how
if (ready) {
func();
} else {
setTimeout(function () {
check(ready, fund);
}, 1); // check every msec
}
}
但这似乎是一种资源繁重的方式,因为我每隔1毫秒触发相同的函数,直到资源被加载。
这是完成此问题的正确途径吗?
答案 0 :(得分:4)
使用1毫秒定时回调的状态检查器 - 但这似乎是一种资源繁重的方式;这是完成这个问题的正确途径吗?
没有。你应该看一下Promises。这样,您可以轻松地将其表达为:
var a1 = getPromiseForAjaxResult(ressource1url);
var a2 = getPromiseForAjaxResult(ressource2url);
var a3 = getPromiseForAjaxResult(ressource3url);
a1.then(function(res) {
append(res);
return a2;
}).then(function(res) {
append(res);
return a3;
}).then(append);
例如,jQuery的.ajax
函数实现了这一点。
答案 1 :(得分:2)
您可以尝试这样的事情:
var resourceData = {};
var resourcesLoaded = 0;
function loadResource(resource, callback) {
var xhr = new XMLHttpRequest();
xhr.onload = function() {
var state = this.readyState;
var responseCode = request.status;
if(state == this.DONE && responseCode == 200) {
callback(resource, this.responseText);
}
};
xhr.open("get", resource, true);
xhr.send();
}
//Assuming that resources is an array of path names
function loadResources(resources) {
for(var i = 0; i < resources.length; i++) {
loadResource(resources[i], function(resource, responseText) {
//Store the data of the resource in to the resourceData map,
//using the resource name as the key. Then increment the
//resource counter.
resourceData[resource] = responseText;
resourcesLoaded++;
//If the number of resources that we have loaded is equal
//to the total number of resources, it means that we have
//all our resources.
if(resourcesLoaded === resources.length) {
//Manipulate the data in the order that you desire.
//Everything you need is inside resourceData, keyed
//by the resource url.
...
...
}
});
}
}
如果某些组件必须之前加载并执行(如某些JS文件)其他组件,您可以排队AJAX请求,如下所示:
function loadResource(resource, callback) {
var xhr = new XMLHttpRequest();
xhr.onload = function() {
var state = this.readyState;
var responseCode = request.status;
if(state == this.DONE && responseCode == 200) {
//Do whatever you need to do with this.responseText
...
...
callback();
}
};
xhr.open("get", resource, true);
xhr.send();
}
function run() {
var resources = [
"path/to/some/resource.html",
"path/to/some/other/resource.html",
...
"http://example.org/path/to/remote/resource.html"
];
//Function that sequentially loads the resources, so that the next resource
//will not be loaded until first one has finished loading. I accomplish
//this by calling the function itself in the callback to the loadResource
//function. This function is not truly recursive since the callback
//invocation (even though it is the function itself) is an independent call
//and therefore will not be part of the original callstack.
function load(i) {
if (i < resources.length) {
loadResource(resources[i], function () {
load(++i);
});
}
}
load(0);
}
这样,在上一个文件加载完成之前,不会加载下一个文件。
如果您无法使用任何第三方库,则可以使用我的解决方案。但是,如果您执行Bergi suggested并使用Promises,您的生活可能会更容易。
答案 2 :(得分:1)
无需每毫秒调用check()
,只需在xhr onreadystatechange
中运行即可。如果您提供更多代码,我可以进一步解释。
答案 3 :(得分:1)
我会有一个要执行的函数队列,每个函数都会在执行之前检查先前的结果是否已完成。
var remoteResults[]
function requestRemoteResouse(index, fetchFunction) {
// the argument fetchFunction is a function that fetches the remote content
// once the content is ready it call the passed in function with the result.
fetchFunction(
function(result) {
// add the remote result to the list of results
remoteResults[index] = result
// write as many results as ready.
writeResultsWhenReady(index);
});
}
function writeResults(index) {
var i;
// Execute all functions at least once
for(i = 0; i < remoteResults.length; i++) {
if(!remoteResults[i]) {
return;
}
// Call the function that is the ith result
// This will modify the dom.
remoteResults[i]();
// Blank the result to ensure we don't double execute
// Store a function so we can do a simple boolean check.
remoteResults[i] = function(){};
}
}
requestRemoteResouse(0, [Function to fetch the first resouse]);
requestRemoteResouse(1, [Function to fetch the second resouse]);
requestRemoteResouse(2, [Function to fetch the thrid resouse]);
请注意,为了简单起见,目前这是O(n ^ 2),如果您在具有hasRendered属性的remoteResults的每个索引处存储了一个对象,它会变得更快但更复杂。然后你只会扫描回来,直到找到一个尚未发生的结果或一个已经渲染的结果。