javascript - CasperJS 注入(inject)的客户端 JavaScript 未完全加载?

标签 javascript jquery ajax phantomjs casperjs

我目前正在使用

注入(inject) include.js
casper.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/

相关文章:

javascript - 使用重叠标记 Spiderfier 时获取 map 标记的新位置

javascript - 如何在没有事件的情况下调用 ember 辛烷模板内的函数?

jquery - 具有相同文本区域名称的多个 ckeditor 实例

javascript - Jquery ajax调用将成功值分配给窗口

javascript - 使用ajax动态更改显示的数据

javascript - Google 脚本方法 getLastRow 获取 null

javascript - Knockout.js 根据另一个下拉列表更改下拉列表的可能值

jquery - 在添加每个 li 时使 ul 向上移动

javascript - JqG​​rid 检查行是否被选中

jquery - JSF 和 Jquery AJAX - 如何让它们一起工作?