短篇小说:
我想解析一个有无限滚动的网站,我不想实现无限滚动。所以我想创建一个脚本,从浏览器控制台自动滚动页面等待数据出现然后重复直到结束。
长篇故事:
我正在尝试使用javascript控制台向我的浏览器向下滚动无限滚动。当我们滚动到底部时,会进行Ajax调用并填充<div>
元素,因此我们必须等待这种情况发生,然后重新开始我们的过程。
我的主要问题是所有这一切都做得太快,它不会在恢复进程之前等待ajax完成。
举一个具体的例子,当我进入AngelList工作页面(需要登录)并将其放入我的浏览器控制台时:
function sleep(µs) {
var end = performance.now() + µs/1000;
while (end > performance.now()) ; // do nothing
}
var loading = true;
$(window).load(function () {
loading = false;
}).ajaxStart(function () {
loading = true;
}).ajaxComplete(function () {
loading = false;
});
function waitAfterScroll() {
if(loading === true) {
console.log("Wait the Ajax to finish loading");
setTimeout(waitAfterScroll, 1000);
return;
}
console.log("Ajax DONE");
}
var X= 0;
while(X < 100){
sleep(1000000);
X = X + 10;
console.log(X);
window.scrollTo(0,document.body.scrollHeight);
waitAfterScroll();
}
我得到了这个结果:
10
Wait the Ajax to finish loading
20
Wait the Ajax to finish loading
30
Wait the Ajax to finish loading
40
Wait the Ajax to finish loading
50
Wait the Ajax to finish loading
60
Wait the Ajax to finish loading
70
Wait the Ajax to finish loading
80
Wait the Ajax to finish loading
90
Wait the Ajax to finish loading
100
Wait the Ajax to finish loading
Wait the Ajax to finish loading
Ajax DONE
我想要的是:
10
Wait the Ajax to finish loading // one or multiple times.....
Ajax DONE
20
Wait the Ajax to finish loading // one or multiple times.....
Ajax DONE
30
Wait the Ajax to finish loading // one or multiple times.....
Ajax DONE
40
Wait the Ajax to finish loading // one or multiple times.....
Ajax DONE
50
Wait the Ajax to finish loading // one or multiple times.....
Ajax DONE
60
Wait the Ajax to finish loading // one or multiple times.....
Ajax DONE
70
Wait the Ajax to finish loading // one or multiple times.....
Ajax DONE
80
Wait the Ajax to finish loading // one or multiple times.....
Ajax DONE
90
Wait the Ajax to finish loading // one or multiple times.....
Ajax DONE
100
Wait the Ajax to finish loading // one or multiple times.....
Ajax DONE
我希望这很清楚。
换句话说,我希望能够向下滚动,停止执行javascript或者至少等待ajax完成加载,然后重复。
答案 0 :(得分:3)
我很确定我误解了你想要的东西,但无论如何。为什么不使用Promises?:
var promise = new Promise(function(resolve, reject) {
var req = new XMLHttpRequest();
req.open('GET', url);
req.onload = function() {
if (req.status == 200) {
resolve(req.response);
}
};
});
promise.then(function(result) {
window.scrollTo(0,document.body.scrollHeight);
})
或者,您可以创建一个同步的ajax请求来停止javascript执行。
jQuery.ajax({
url: "someurl.html",
async: false,
success: function(html){
window.scrollTo(0,document.body.scrollHeight);
}
});
但是,出于性能原因,我不建议这样做。相反,你可以:
// Start off with a promise that always resolves
var sequence = Promise.resolve();
arrayOfWebsiteContentUrls.forEach(function(url) {
sequence = sequence.then(function() {
return fetchTheContent(url);
}).then(function(content) {
addContent(content);
window.scrollTo(0,document.body.scrollHeight);
});
});
我从this excelent article on Promises获取了最后一位。
如果有什么是你没有得到的,请告诉我。