2013-03-08 21 views
9

Sto usando cercando di utilizzare nodejs e phantomjs sul lato server per la SEO del nostro sito. Mentre ajax funziona bene, non sono in grado di eseguire promesse personalizzate che ho usato nel mio codice. Come faccio a fare in modo che phantomJS aspetti fino a quando le promesse non saranno risolte. Di seguito è quello che ho codificato.Come si eseguono jQuery promises in 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 aggiunge 'prima-dom-ready' e 'dopo-dom-ready' di classe, ma sono in grado di ottenere 'promessa-giustiziato' di classe sul corpo.

+0

E 'possibile vedere il tuo script phantomJS completo (così come il codice completo di tutti gli altri file da cui dipende). Cioè in modo che possiamo facilmente riprodurre il problema. –

+0

In quale momento e in che modo stai verificando se la classe 'promise-execution' è stata o non è stata aggiunta? Che tipo di debug hai fatto, ad esempio, hai provato a mettere una chiamata a 'console.log' dopo' dfrd.resolve() '? Hai provato questo codice in un normale browser, in altre parole, cosa ti fa pensare che sia un problema di PhantomJS? –

risposta

4

PhantomJs non attende automaticamente la fine di tutti gli script in sospeso. WebPage # onLoadFinished viene chiamato sull'evento onload.

Come per la maggior parte degli script, l'idea qui è di aspettare che "qualcosa" sia fatto o vero. Consiglio vivamente di provare waitfor.js. È molto importante capire questo esempio in PhantomJs.

Suppongo che il tuo esempio sia un esempio, ma lasciami proporre una risposta.

Html Page

<!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 Script

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

In sostanza, waitFor controllerà ogni 500 ms se il corpo ha una classe denominata 'promise-executed'.

+0

Grazie per la risposta dettagliata .. Dovrò fare un po 'più di lettura prima di incorporare nei miei test, ma questo sembra ragionevole e ben documentato .. –

+0

sì, questo funziona per me. Spero che questo ti possa aiutare. – Cybermaxs

Problemi correlati