CasperJS注入的客户端javascript没有完全加载

CasperJS injected client javascript not being loaded fully?

本文关键字:加载 javascript 注入 客户端 CasperJS      更新时间:2023-09-26

我目前正在使用注入include.js

casper.options.clientScripts.push('./include.js')

这里有include.js(它是为了确保所有ajax请求都完成:使用$.ajaxStop()来确定页面何时在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

所以有时候我的代码在等待窗口时会超时_allAjaxRequestsHaveStopped变为true,而其他时候它会正常工作。我还在我知道有ajax请求的同一个页面上进行测试。有人知道如何解决这种矛盾吗?

明白了!因此,在似乎只加载了部分脚本的地方,当它到达$(document).ajaxStop()时确实出现了错误,因为页面上还没有加载jQuery。CasperJS有时会在加载jQuery后注入include文件,这就是它有时工作的原因。

通过下载jQuery并在include文件之前手动注入修复了它:

casper.options.clientScripts.push('./jquery-2.1.4.min.js')
casper.options.clientScripts.push('./include.js')