如何在phantomJS中执行jQuery Promise? [英] How do I execute jQuery promises in phantomJS?

查看:161
本文介绍了如何在phantomJS中执行jQuery Promise?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在服务器端将nodejs和phantomjs用于我们网站的SEO.尽管ajax可以正常工作,但是我无法执行我在代码中使用过的自定义诺言.我如何让phantomJS等到承诺被解决. 以下是我编写的代码.

I'm using trying to use nodejs and phantomjs on the server-side for SEO of our site. While ajax works fine, I'm not able to execute custom promises that I've used in my code. How do I make phantomJS wait till the promises are resolved. Below is what I have coded.

$('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添加了"bedom-dom-ready"和"after-dom-ready"类,但我无法在主体上获得"promise-execute"类.

phantomJS adds 'before-dom-ready' and 'after-dom-ready' class, but I'm unable to get 'promise-executed' class on body.

推荐答案

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

PhantomJs does not automatically wait the end of all pending scripts. WebPage#onLoadFinished is called on the onload event.

对于大多数脚本来说,这里的想法是等到某事"完成或成立. 我强烈建议您测试 waitfor.js .了解PhantomJs中的示例非常重要.

As for most of the scripts, the idea here is to wait until "something" is done or true. I highly suggest you to test waitfor.js. It is really important to understand this example in PhantomJs.

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

I suppose your example is an example, but let me propose an answer.

HTML页面

<!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);
        }
    });
}

基本上,如果主体具有名为'promise-executed'的类,则waitFor将每500毫秒检查一次.

Basically, waitFor will check every 500 ms if body has a class named 'promise-executed'.

这篇关于如何在phantomJS中执行jQuery Promise?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆