Kishore
Kishore

Reputation: 1912

PhantomJS updating resource file path

I have a nodejs+phantomjs setup. I am trying to generate html and serve it to the bot for seo. The app currently works but I want to improve the performance. Since a lot of js files are loaded, I am trying to update resource path in phantomjs so that the resources are pointed to local rather than making a http request in browser to improve the performance.

I am doing something like this.

page.onResourceRequested = function (requestData, request) {

  if(requestData.url.indexOf('.js') > 0) {
    requestData.url = requestData.url.replace("http://foo.com/","/path to local directory of the resources");

  }

But this doesnt seem to work. In the network tab i still see resources pulled from external source.

Is there any alternative approach? I also looked at caching in phantomjs that doesnt seem to help.

Help is much appreciated. Thanks.

Upvotes: 2

Views: 1205

Answers (1)

Kishore
Kishore

Reputation: 1912

Just found the solution after looking at the documentation.

onResourceRequested

requests a resource. The first argument to the callback is the requestData metadata object. The second argument is the networkRequest object itself.

Example:

page.onResourceRequested = function(requestData, networkRequest) {
   console.log('Request (#' + requestData.id + '): ' + JSON.stringify(requestData)); 
}; 
  • abort(): aborts the current network request. Aborting the current network request will invoke (onResourceError) callback.

  • changeUrl(url): changes the current URL of the network request.

request.changeUrl(url) can be used to change the url.

http://phantomjs.org/api/webpage/handler/on-resource-requested.html

Upvotes: 3

Related Questions