0

I have a client side JS library(call it lib.js) which uses jQuery. The library fires an API using ajax and renders html based on the json response received.

Due to SEO concerns, I want to create another nodejs based API, which does all the client side work that lib.js does and creates html on the server side and responds with this html. The catch is that I want to use the same client side library(lib.js) on the server side too so that any changes made to lib.js affects the html response of my backend API too.

So, basically I am looking to execute client side JS on the server without doing too many changes to client side JS library.

I went through node modules of jquery and jsdom but could not find a conclusive way to approach this solution. Are there any better node modules to do this ? Is there any good article that targets this problem ?

Anuj
  • 78
  • 1
  • 8
  • Have you considered using ReactJS ? Server-side rendering works pretty well with nodejs and react. You still can use jQuery with it as long as you keep the jQuery code inside `componentDidMount()` lifecycle hook as there is no DOM in nodeJS it will never be executed. – flocks Jul 04 '17 at 15:11
  • Thanks @flocks but ReactJS is not an option. – Anuj Jul 05 '17 at 11:50

1 Answers1

0

I am not sure that there is a way to do that and it is hard to tell which library/program is capable of all that. One thing might be the use of phantom and export the resulting html after page load there. Another thing could be jsdom, which tells from itself that is it capable of executing scripts, and use the resulting html from there. But both options have the downside that all attached event listeners will be lost if you just use the html from there. Also the onload event will be triggered again, so your scripts might go crazy, if the dom already exists. All in all I doubt that this will work good, but it also depends on the scripts and what they are doing.

philipp
  • 15,947
  • 15
  • 61
  • 106