如何在 phantomJS 中执行 jQuery Promise?

2024-02-29

我正在尝试在服务器端使用 nodejs 和 phantomjs 来对我们的网站进行 SEO。虽然 ajax 工作正常,但我无法执行我在代码中使用的自定义承诺。我如何让 phantomJS 等到承诺得到解决。 下面是我编码的内容。

$('body').addClass('before-dom-ready');

$(function() {
    $('body').addClass('after-dom-ready');

    var dfrd = $.Deferred(),
            promise = dfrd.promise();

    setTimeout(function() {
        dfrd.resolve();
    }, 5000);

    promise.done(function() {
        $('body').addClass('promise-executed');
    });

});

phantomJS 添加了“before-dom-ready”和“after-dom-ready”类,但我无法在主体上获取“promise-execulated”类。


PhantomJs 不会自动等待所有待处理脚本的结束。 WebPage#onLoadFinished 在 onload 事件上调用。

对于大多数脚本来说,这里的想法是等到“某事”完成或成真。 我强烈建议你测试一下waitfor.js https://github.com/ariya/phantomjs/blob/master/examples/waitfor.js。理解 PhantomJs 中的这个例子非常重要。

我想你的例子只是一个例子,但让我提出一个答案。

网页

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <script type="text/javascript" src="http://code.jquery.com/jquery-1.10.0.min.js"></script>
    <title>Test</title>
</head>
<body id="body">

    <script type="text/javascript">
        //alert('hello');
        $('body').addClass('before-dom-ready');

        $(function () {
            $('body').addClass('after-dom-ready');

            var dfrd = $.Deferred(),
                    promise = dfrd.promise();

            setTimeout(function () {
                dfrd.resolve();
            }, 5000);

            promise.done(function () {
                $('body').addClass('promise-executed');
                $('body').text('Hello World !');
            });

        });
    </script>
</body>
</html>

PhantomJs 脚本

var page = require('webpage').create();
var system = require('system');

function waitFor(testFx, onReady, timeOutMillis) {
    var maxtimeOutMillis = timeOutMillis ? timeOutMillis : 10000, //< Default Max Timout is 10s
        start = new Date().getTime(),
        condition = false,
        interval = setInterval(function () {
            if ((new Date().getTime() - start < maxtimeOutMillis) && !condition) {
                // If not time-out yet and condition not yet fulfilled
                condition = (typeof (testFx) === "string" ? eval(testFx) : testFx()); //< defensive code
            } else {
                if (!condition) {
                    // If condition still not fulfilled (timeout but condition is 'false')
                    //console.log("'waitFor()' timeout");
                    typeof (onReady) === "string" ? eval(onReady) : onReady();
                    clearInterval(interval);
                    //phantom.exit(1);
                } else {
                    // Condition fulfilled (timeout and/or condition is 'true')
                    console.log("'waitFor()' finished in " + (new Date().getTime() - start) + "ms.");
                    typeof (onReady) === "string" ? eval(onReady) : onReady(); //< Do what it's supposed to do once the condition is fulfilled
                    clearInterval(interval); //< Stop this interval
                }
            }
        }, 500); //< repeat check every 500ms
};

if (system.args.length != 1) {
    console.log('invalid call');
    phantom.exit(1);
} else {
    //adapt url to your context
    page.open('http://localhost:9231/demo.html', function (status) {
        if (status !== 'success') {
            console.log('Unable to load the address!');
            phantom.exit();
        } else {
            waitFor(
                function () {
                    return page.evaluate(function () {
                        return $('body').hasClass('promise-executed');
                    }) > 0;
                },
                function () {
                    page.render('page.png');
                    phantom.exit();
                }, 10000);
        }
    });
}

基本上,waitFor将每 500 毫秒检查 body 是否有一个名为的类'promise-executed'.

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何在 phantomJS 中执行 jQuery Promise? 的相关文章

随机推荐

  • 使用 numpy/scipy 的快速 B 样条算法

    我需要在 python 中计算 bspline 曲线 我研究了 scipy interpolate splprep 和其他一些 scipy 模块 但找不到任何可以轻松满足我需要的东西 所以我在下面编写了自己的模块 代码运行良好 但速度很慢
  • 如何保护 web.config 中存储的密码的安全?

    我在 web config 文件中添加了以下设置 以启动对外部系统的 API 调用 因此 我存储 API URL 用户名 密码 如下所示
  • 包含 MySQL 查询结果中未找到的值

    我有以下 MySQL 表 tbl pet owners id name pet city date adopted 1 jane cat Boston 2017 07 11 2 jane dog Boston 2017 07 11 3 ja
  • cygwin中如何杀死进程?

    您好 我有以下无法杀死的进程 我在 windows xp 32 位中运行 cygwin 我尝试发出以下命令 bin kill f 4760 bin kill 9 5000 kill 9 5000 kill 5000 当我写 bin kill
  • 如何在 .net 中获取可用的 wifi AP 及其信号强度?

    有没有办法使用 NET 访问所有 WiFi 接入点及其各自的 RSSI 值 如果我可以在不使用非托管代码的情况下完成它 那就太好了 或者如果它可以在 Mono 和 NET 中工作 那就更好了 如果可能的话 我将不胜感激代码示例 谢谢 以下是
  • 使用隐藏代码的 nbextensions 时查找并转到文本

    这是来自的重复this https stackoverflow com questions 530245473年前的问题 目前还没有令人满意的解决方案 问题是在使用 nbextensions 时 在 Jupyter Notebook 的所有
  • 虚拟机上奇怪的程序延迟行为

    我编写了一个程序来读取 256KB 数组以获得 1 毫秒的延迟 该程序非常简单并附带 然而 当我在Xen上的VM上运行它时 我发现延迟不稳定 它具有以下模式 时间单位是ms totalCycle CyclePerLine totalms 2
  • 使用 MySQLi 插入 NULL 而不是空值

    我有一个带有一些可选字段的表单 在数据库中 这些字段设置为接受 NULL 如果某些字段为空 下面的代码将引发错误 您能帮忙看看避免这种情况的最佳方法是什么吗 我想到的唯一解决方案是将变量设置为 if isempty query INSERT
  • 从无符号整数中减去有符号整数[重复]

    这个问题在这里已经有答案了 unsigned int value 1860 int data 1300 if data value gt 0 printf Why it is printing this 输出 为什么打印这个 我不明白为什么
  • linux gcc 链接器与 C 程序的问题

    我正在尝试编译一个包含 c 文件标头的 C 程序 但只有 1 个 c 文件真正使用了头文件中定义的变量 这是一些会产生链接器问题的示例代码 我试图让我的头文件包含 2 使用的全局变量 不同的 c 文件 任何类型的帮助将不胜感激 谢谢 tmp
  • directX 创建交换链

    在我的书中 我编写了创建交换链的代码 IDXGIDevice dxgiDevice 0 mD3dDevice gt QueryInterface uuidof IDXGIDevice void dxgiDevice IDXGIAdapter
  • modelBuilder.IncludeMetadataInDatabase 在 EF CTP5 中的位置在哪里?

    使用 CTP4 我曾经能够执行以下操作 如由 ptrandem 建议 https stackoverflow com questions 3600672 entity framework ctp4 code first how to tur
  • Google Cloud Run 屏蔽授权标头中的承载令牌

    Cloud Run 的 Google 文档指出 您可以 从授权标头中提取令牌 文档在这里 https cloud google com run docs authenticating end users getting user profi
  • 字符串数组中的随机元素[关闭]

    很难说出这里问的是什么 这个问题是含糊的 模糊的 不完整的 过于宽泛的或修辞性的 无法以目前的形式得到合理的回答 如需帮助澄清此问题以便重新打开 访问帮助中心 help reopen questions 我有一个字符串数组 String f
  • Heroku 上的 .Net Core 和 Docker

    Context 我正在尝试部署一个ASPNET核心示例应用程序上Heroku https heroku com 与 docker 但不工作 repo https github com mykeels sample web api https
  • 无法通过在 Apache Beam 中创建模板来按所需顺序运行多个管道

    我有两个独立的管道 分别为 P1 和 P2 根据我的要求 我只需要在 P1 完全完成执行后才运行 P2 我需要通过一个模板完成整个操作 基本上 模板在找到 run 方式 即 p1 run 时就被创建 所以我可以看到 我需要使用两个不同的模板
  • 为什么信号处理程序中的 waitpid 需要循环?

    我在一本电子书中读到 waitpid 1 status WNOHANG 应该放在 while 循环下 这样如果多个子进程同时退出 它们都会被收获 我尝试了这个概念 同时创建和终止 2 个子进程 并通过 waitpid 不使用循环来获取它 并
  • 每个日期的 SQL 总金额

    我有一个名为 rentals 的表 其中存储如下数据 id rent id start date end date amount 1 54 12 10 2019 26 10 2019 100 2 54 13 10 2019 20 10 20
  • 检查一个列表是否是 pandas Dataframe 中另一个列表的子集

    所以 我有这个包含近 3000 行的 Dataframe 看起来像这样 CITIES 0 A B 1 A B C D 2 A B C 4 X 5 X Y Z 2670 Y Z 我想从 DF 中删除 CITIES 列表包含在另一行中的所有行
  • 如何在 phantomJS 中执行 jQuery Promise?

    我正在尝试在服务器端使用 nodejs 和 phantomjs 来对我们的网站进行 SEO 虽然 ajax 工作正常 但我无法执行我在代码中使用的自定义承诺 我如何让 phantomJS 等到承诺得到解决 下面是我编码的内容 body ad