我目前正在使用
注入(inject) include.jscasper.options.clientScripts.push('./include.js')
这是 include.js (它是为了确保所有 ajax 请求都完成: Using $.ajaxStop() to determine when page is finished loading in CasperJS )
(function(){
window._allAjaxRequestsHaveStopped = false;
var interval;
console.log('injecting include js')
$.ajaxSetup({'global':true});
$(document).ajaxStop(function() {
console.log('NO MORE outstanding ajax calls');
if (interval) {
clearInterval(interval);
interval = null;
}
interval = setTimeout(function() {
window._allAjaxRequestsHaveStopped = true;
}, 1000);
});
$(document).ajaxStart(function() {
console.log('NEW ajax call');
if (interval) {
clearInterval(interval);
interval = null;
}
});
console.log('include js loaded');
})();
问题是有时 ajaxStop 和 ajaxStart 函数不会被加载,但它总是输出第一个 console.log 'injecting include js'。
CasperJS脚本
casper.waitForAjax = (callback) ->
fn_wait = ->
casper.evaluate ->
return window._allAjaxRequestsHaveStopped
casper.waitFor fn_wait, callback
casper.options.clientScripts.push('./include.js')
casper.options.waitTimeout = 10000
describe 'Main Test', ->
before ->
casper.start 'url', ->
phantom.clearCookies()
it 'Test Case 1', ->
casper.then ->
@click 'button'
casper.waitForAjax ->
// Move on with test
因此,有时我的代码会在等待 window._allAjaxRequestsHaveStopped 变为 true 时超时,而其他时候则可以正常工作。我还在我知道有 ajax 请求的同一页面上进行测试。有谁知道如何解决这种不一致?
最佳答案
明白了!因此,看起来只加载了脚本的一部分,但实际上在到达 $(document).ajaxStop() 时就出现了错误,因为 jQuery 尚未加载到页面上。 CasperJS 有时会在加载 jQuery 后注入(inject)包含文件,这就是它有时能工作的原因。
通过下载 jQuery 并在包含文件之前手动注入(inject)它来修复它:
casper.options.clientScripts.push('./jquery-2.1.4.min.js')
casper.options.clientScripts.push('./include.js')
关于javascript - CasperJS 注入(inject)的客户端 JavaScript 未完全加载?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31033375/