var page = require('webpage').create(), system = require('system'), isDev = false, reRunNum = 2, resourceError = null; if (system.args.length < 3) { phantom.exit(1); } if (system.args[3]) { isDev = true; } if (isDev) { console.log(navigator.userAgent); var s = (new Date()).getTime(); page.onConsoleMessage = function (msg) { console.log(msg); }; page.onError = function (msg, trace) { console.log(msg + ';;errInfo' + JSON.stringify(trace)); } } else { console.log = function () { }; } page.onResourceError = function (error) { if (error.url == system.args[1]) { console.log('pageLoadError:' + JSON.stringify(error)); resourceError = error; } }; _run(); setTimeout(function () { console.log('pageTimeOut'); phantom.exit(2); }, 20000) function _run() { page.open(system.args[1], function (status) { if (status == 'fail') { if (!_reRun()) { phantom.exit(2); } return; } var staticWaitNum = 10, pageWaitNum = 15, cd = 200, over, resources = {}, start = false, initRender = false; page.onResourceRequested = function (request) { if (!start) { start = true; } resources[request.id + ''] = 0; console.log('request -' + request.id + ':' + request.url); } page.onResourceReceived = function (response) { if (!start) { start = true; } if (response.stage == "end") { delete resources[response.id + '']; console.log('response-' + response.id + ':' + response.url); } } function initOver() { clearTimeout(over); over = setTimeout(function () { console.log('time:' + ((new Date()).getTime() - s) + '---resources' + JSON.stringify(resources)); if (resourceError != null && resourceError.status != 200) { phantom.exit(3); } if (!initRender) { console.log('initRender'); initRender = true; page.render(system.args[2]); } if (!start) { if (pageWaitNum-- > 0) { console.log('pageWaitNum:' + pageWaitNum); initOver(); return; } else { if (!_reRun()) { _render(); } return; } } var keys = _keys(resources), k; for (var i in keys) { k = keys[i]; resources[k]++; if (resources[k] > staticWaitNum) { console.log('timeOver:' + k); delete resources[k]; } } if (_keys(resources).length > 0) { initOver(); return; } _render(); }, cd); } initOver(); }); } function _render() { page.render(system.args[2]); console.log('overTime:' + ((new Date()).getTime() - s)); phantom.exit(0); } function _reRun() { if (reRunNum-- > 0) { console.log('reRun'); _run(); return true; } else { return false; } } function _keys(m) { var ks = []; for (var k in m) { if (m.hasOwnProperty(k)) { ks.push(k); } } return ks; }