1
我加載位於我的服務器上用這種簡單的方法.txt文件:的Javascript文本文件加載延遲
function getFileFromServer(url, doneCallback)
{
console.time("getFileFromServer");
var xhr;
xhr = new XMLHttpRequest();
xhr.onreadystatechange = handleStateChange;
xhr.open("GET", url, true);
xhr.send();
function handleStateChange() {
if (xhr.readyState === 4) {
doneCallback(xhr.status == 200 ? xhr.responseText : null);
}
}
console.timeEnd("getFileFromServer");
}
我使用它,在這個簡單的方式,因此這個帖子:Reading a txt file from Server, writing it to website
function loadFile(url) {
console.time("loadFile");
getFileFromServer(url, function(text) {
if (text === null) {
console.log("error-loading-file");
}
else {
console.timeEnd("loadFile");
doStuff(text);
}
});
正如你所看到的,我已經把console.time記錄下來了。下面是瀏覽器控制檯答案:
getFileFromServer:1.744ms
的loadFile:18114.871ms
我不是一個JavaScript專家,我可以找出唯一解釋的時間差是參數傳遞(值與C++中的參考)。有人可以解釋我在時間上的差異嗎?
這是因爲ajax調用的'async'性質。 http://stackoverflow.com/questions/11233633/understanding-asynchronous-code-in-laymans-terms – shakib