Skip to content

Instantly share code, notes, and snippets.

@Kukunin
Created June 30, 2014 19:44
Show Gist options
  • Save Kukunin/f1d43bfec054dd95cd26 to your computer and use it in GitHub Desktop.
Save Kukunin/f1d43bfec054dd95cd26 to your computer and use it in GitHub Desktop.
PhantomJS module to implement robust onLoadFinished callback, supporting redirects, JS resource loading etc
function addAllResourcesLoadedCallback(page, timeout) {
function debug(text) {
if (typeof page.onDebug == "function") {
page.onDebug(text);
}
}
var counter = [], timer;
timeout = timeout || 2000;
page.previousOnResourceRequested = page.onResourceRequested;
page.previousOnResourceReceived = page.onResourceReceived;
page.previousOnResourceTimeout = page.onResourceTimeout;
page.previousOnResourceError = page.onResourceError;
page.onResourceRequested = function(request) {
if ( counter.indexOf(request.id) == -1 ) {
debug("Resource requested. ID is " + request.id + ". URL is " + request.url);
counter.push(request.id);
window.clearTimeout(timer);
}
}
page.onResourceReceived = function(resource) {
debug("Resource received. Stage is " + resource.stage + ". ID is " + resource.id + ". Counter is " + counter.length + ". Redirect URL is " + resource.redirectURL);
if ( resource.stage != "end" && !resource.redirectURL ) return;
var i = -1;
if ( (i = counter.indexOf(resource.id)) == -1 ) return;
//Remove element from array
counter.splice(i,1);
debug("Resource is loaded");
if ( counter.length == 0 ) {
debug("Requests counter is empty");
timer = window.setTimeout(function() {
debug(3, "Call the onAllResourcesLoaded callback");
if (typeof page.onAllResourcesLoaded == "function") {
page.onAllResourcesLoaded();
}
}, timeout);
}
}
page.onResourceError = page.onResourceReceived;
page.onResourceTimeout = page.onResourceReceived;
};
module.exports = {
addAllResourcesLoadedCallback: addAllResourcesLoadedCallback
};
@Kukunin
Copy link
Author

Kukunin commented Jun 30, 2014

It is hard to catch the event in the PhantomJS, when the page is really loaded.

There is may be Javascript redirects, AJAX calls, etc. This snippet tracks all resource requests, and fire the onAllResourcesLoaded event, when all resources are loaded. There is 2 sec (by default) delay, between all resources are loaded and callback is fired to make sure, the page has enough time to initialize all resource loads (it is useful, when there is javascript, which will load extra data when page is loaded)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment