Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I render an html file in javascript?

OK, I am using javascript sever side, including node.js. Because of performance issues, we have decided to move one page to being rendered server-side, not client side, so the server returns a stream of html, fully rendered, back to the client.

I have seen this question and the related answers, but wondered if this was the best or right approach. In particular, what is the most appropriate way to render a page, and run all of the javascript on it within a js or node.js call?

Ideas that I have looked at:

  1. Call the javascript code directly on the page, and invert everything to make it generate the html items needed. As this is urgent, I would rather avoid re-writing any more than I have to.

  2. Render a document, with a simple iframe to generate the html. But how do I point to the page in the iframe, as I am server side? Surely this is just adding another level of abstraction to the same problem.

  3. Using the ideas detailed above, but I am wondering whether this is the right route, given some of the problems I have seen encountered with it.

EDIT: Just to clarify - I want to, in effect, load the html page in a browser, let it finish rendering, and then capture the entire generated html for passing through to the client (saving the time to render on the client).

like image 762
Schroedingers Cat Avatar asked Aug 28 '13 11:08

Schroedingers Cat


People also ask

How do I render an HTML file?

We will attach the HTML file to the response object, as shown here. Copy let http = require('http'); let fs = require('fs'); let port = 8080; const server = http. createServer((request, response) => { response. writeHead(200, { 'Content-Type': 'text/html' }); fs.

How do you render in JavaScript?

The Render Function render() function takes two arguments, HTML code and an HTML element. The purpose of the function is to display the specified HTML code inside the specified HTML element.


2 Answers

This is a simple example that does server-side templating (no express): https://github.com/FissionCat/handlebars-node-server-example

This is an example that serves html, js, css and an mp3 (but doesn't use express or any templating): https://github.com/FissionCat/Hue-Disco

like image 118
Timespace Avatar answered Oct 20 '22 00:10

Timespace


There's some pretty useful documentation found here: http://www.hongkiat.com/blog/node-js-server-side-javascript/

Like you said, avoiding lots of rewriting is a bonus.

like image 45
user5623896726 Avatar answered Oct 19 '22 23:10

user5623896726