Does comet server data in the iframe just accumulate? - node.js

I push [script]dosomething()[/script] tags into the iframe for my comet server using chunked data, but script tags just continues to accumulate forever. How do I wipe it after every script tag?

Wipe script tag
P.S: When you want to wipe script tags it is probably to follow Does comet server data in the iframe just accumulate?
I believe you should close the connection after sometime(no good, see Does comet server data in the iframe just accumulate? instead) which automatically frees up the memory associated with that request. You then off course need to reconnect. This page says something else even:
"Page Streaming" means the browser
discovers server changes almost
immediately. This opens up the
possibility of real-time updates in
the browser, and allows for
bi-directional information flow.
However, it's quite a departure from
standard HTTP usage, which leads to
several problems. First, there are
unfortunate memory implications,
because the Javascript keep
accumulating, and the browser must
retain all of that in its page model.
In a rich application with lots of
updates, that model is going to grow
quickly, and at some point a page
refresh will be necessary in order to
avoid hard drive swapping, or a worse
fate.
This advices to reload the page which is also an option. But I think closing that connection(iframe) and reconnecting might also work.
Comet has a lot of problems you need to hack around:
As you can read from this WIKI page it also has problems with "reliable error handling method, and the impossibility of tracking the state of the request calling process.".
Also Internet Explorer needs to sent some junk to get the process started(see http://cometdaily.com/2007/11/05/the-forever-frame-technique/)
That's why I again recommend you to use socket.io(see below) which takes care of all this nonsense.
Socket.io
I advice you to use socket.io instead, which is very good product. It is supported by all major browsers. As you can see it support a lot of transport(XHR, Websockets, etc) and choices the best one available on your browser for the best performance.

Wipe script tag without reconneting
You can remove script tag every time that it is executed by adding some code when the server prints chunk.
<script type="text/javascript">
// Calls your message handler
app.handle("Hello World");
// Removes this script element
var scripts = document.getElementsByTagName("script"),
elem = scripts[scripts.length - 1];
elem.parentNode.removeChild(elem);
</script>
Compressed version
<script type="text/javascript">
app.handle("Hello World");
(function(){var a=document.getElementsByTagName("script"),a=a[a.length-1];a.parentNode.removeChild(a)})();
</script>
But, Hidden Iframe or Forever Iframe is too annoying to use as Alfred mentioned. Personally, I think this classical way makes Comet look graceless and charmless.
jQuery Stream
My recommendation is to use jQuery Stream, which provides the unified two-way communication interface over WebSocket and HTTP protocol. It is a light-weight client-side JavaScript Library such as jQuery.
The enhanced Iframe transport being used by jQuery Stream is different from the classical one in many ways, requries text/plain response containing only messages instead of text/html response and empties the response every time that it's handled.
According to some user's test, Internet Explorer 8 using enhanced Iframe transport has no problem with messages of several megabytes (unlike Firefox using XMLHttpRequest as transport, which is really struggling).

Related

What is the difference between server side rendering (Next.js) and Static Site rendering (Gatsby.js)?

I'm looking to create a website that does not rely on client-side JavaScript, however, I still want to use SPA features like client-side routing etc, so I am looking at using a framework that does not render on the client-side. These 2 seem to be the top options for this type of thing, however, I'm unsure as to the differences between the 2 different types of server processing.
Server side rendering is where a request is made from the client/browser to the server, and then at that point the HTML is generated on-the-fly run-time and sent back to the browser to be rendered.
Static site rendering is very similar, however the parsing is carried out during the build time instead. Therefore when a request is made the HTML is stored statically and can be sent straight back to the client.
They both have their pros and cons:
Although static sites will be faster at run-time as no server-side processing is required, it does mean that any changes to data require a full rebuild over the application server side.
Alternatively, with the server side approach, putting any caching aside, the data is processed on-the-fly and sent straight to the client.
Often the decision is best made depending on how dynamic and real-time your content must be vs how performant the application needs to be.
For example, Stackoverflow most likely uses a server-side rendering approach. There are far two many questions for it to rebuild static versions of every question page each time a new post is submitted. The data also needs to be very real-time with users being able to see posts submitted only seconds ago.
However, a blog site, or promo site, which hardly has any content changes, would benefit much more from a static site setup. The response time would be much greater and the server costs would be much lower.

Which method is faster, express : Server-side rendering vs client-side rendering

What I would like to know is, how do you built your web application? I'm really confuse as which method should I use for my project.
Already decided which technologies to choose.
1) Node.js and express as its Framework
2) MongoDB
3) React + Flux
But the problem right now, should I use method (A) or method (B)
Method (A) - Serverside rendering for HTML
app.get('/users/', function(request, respond) {
var user = "Jack";
respond.render("user", { user: user });
});
Method (B) - Clientside rendering for HTML
app.get('/users/', function(request, respond){
var user = "Jack";
respond.json({ user: user });
});
Method A will render the HTML from the server and as well as the data.
Method B will just respond the data that is needed for the client which is React.js, so that it could manipulate the data.
My concern, is which method should I use? most startups use which method?
Thank you.
It's not an either/or proposition.
React is a client side framework. You have to render on the client side. The question is whether to render on the server side in addition to rendering on the client side.
The answer? If you can, YES!
You will get SEO benefits and an initial performance boost by rendering on the server side. But you will still have to do the same client side rendering.
I suggestion googling "isomorphic react" and doing some reading. Here is one article on the subject.
http://www.smashingmagazine.com/2015/04/react-to-the-future-with-isomorphic-apps/
Well, it really depends on which vision you have on the modern web, and what you are willing to do.
Will you prefer to let your users wait, displaying a loader while data are loaded asynchronously, or will you prefer to keep your users busy as long as you can ?
Here are different articles that will help you clear your mind and be aware of the different advantages that you can have by doing server-side rendering, client-side rendering having multiple issues.
You can see this post from Twitter blog saying they improve their initial page load by 1/5th to what they had before, by moving the rendering to the server:
https://blog.twitter.com/2012/improving-performance-on-twittercom
An other article, this time from airbnb, describing the issues you can have with client-side rendering itself:
http://nerds.airbnb.com/isomorphic-javascript-future-web-apps/
There is also an other interesting article talking about client-side/server-side rendering, bringing a debate on when should we use / not use server-side or client-side rendering and why:
https://ponyfoo.com/articles/stop-breaking-the-web
And to finish, I can give you two more link more focused on react, and describing in which way server-side rendering should be helpful for your case:
https://www.terlici.com/2015/03/18/fast-react-loading-server-rendering.html
http://reactjsnews.com/isomorphic-javascript-with-react-node/
Now, about what you SHOULD do, it's a matter of what you exactly need to do, to my opinion, but basically, you can do both at the same time (client-side AND server-side), to have the best user experience.
This concept is called "isomorphic javascript" and it is getting more and more popular these days.
The simplest architecture is to just do dynamic html rendering on the server, with no Ajax, and with a new HTML page requested for pretty much any client click. This is the 'traditional' approach, and has pros and cons.
The next simplest is to serve completely static html+js+css (your React app) to the client, and make XMLHttpRequest calls to webservices to fetch the required data (i.e. your method B).
The most complex but ideal approach (from a performance and SEO perspective) is to build an 'isomorphic' app that supports both approaches. The idea is that the server makes all the necessary WS calls that the client would make and renders the initial page that the user has visited (which could be a deep-linked part of the application), a bit like option A but using React to do the rendering, and then passes control to the client for future DOM updates. This then allows fast incremental updates to the page via web-service calls as the user interacts (e.g. just like B). Navigation between different 'pages' at this point involves using the History API to make it look like you're changing page, when actually you are just manipulating the current page using web-services. But you you then did a browser refresh, your server would send back the full HTML of the current page, before passing control to client-side React again. There are lots of React+Flux+Node examples of this approach available online, using the different flavours of Flux that support server-side rendering.
Whether that approach is worthwhile depends on your situation. It probably makes sense to start using approach B (you can share the your HTTP API between mobile apps and websites), but use a Flux architecture that supports server-side rendering and keep it in mind. That way, if you need to improve the performance of initial page loads, you have the means to do it.

Server-side or client-side {{mustache}}?

{{mustache}} is, in my opinion, a great template library. The question I face is whether to use it in the client-side, or in the server-side.
I am developing an online magazine that will have a main page with one big article and the the rest of its articles in smaller size underneath.
E.g.
+-------------------------------------------------+
| |
| Big Article Image |
| |
| |
+-------------------------------------------------+
Title
Author
+------------+ +------------+ +-----------+
| Image | | Image | | Image |
+------------+ +------------+ +-----------+
Title Title Title
Author Author Author
...
Server-side option
Using {{mustache}} in the server-side, as a PHP library: when the browser asks for the page, the server will complete the template and send it back.
pros:
Loading times will be better. The browser, once it has received the html code will know which other resources it has to ask the server for.
cons:
It will be difficult to integrate with client-side {{mustache}} because when the template is parsed, all the "mustache-tags" that were not matched are removed (I do not know if this can be easily and cleanly avoided).
I do not like to modify the interface from the server-side, I rather do it from the client-side, thus the 3-tier architecture seems more clear (you might differ with this).
I do not have previous experience with server-side {{mustache}}.
Client-side option
Instead of plain {{mustache}} I usually use ICanHas.js, which wraps {{mustache}} and makes it incredibly easy and comfortable: when the browser asks for the page, the HTML is sent, containing all th js code to ask the server for the JSON which contains the title, author, and filename of the image.
pros:
Enhances 3-tier architecture.
Things like infinite scrolling (an other ajax stuff) are super-simple to add.
cons:
Load time is worsen. The browser will need to receive the code, make a request for the JSON, and then ask the server for the resources discovered in that JSON (like the image filename).
Question
Which one do you think, from your experience, is the best solution? Why?
I'd like to add a couple of points to your pros & cons.
Client side templating is more error-prone than server side
With all kind of browsers, versions, devices and security settings, things can quickly get messed up. The more javascript and client-side templating you have on the page, the more likely you'll have some users getting a screwed up page. Think of IE default compatibility settings for instance, a pain. With server side templating, you just have to check it once and be happy.
Client side templating is typically harder to debug than server side
First, you typically don't notice it when a client gets an error in the browser, except if you have some reporting system. Then, you get some cryptic one-liner error message. On server side, on the other hand, you can automatically monitor errors and have nice stack traces where it happen. Sweet ...saves a lot of time.
Probably better SEO with server side templating
It is straightforward for bots to accurately parse static or server generated pages. For pages full of client side templating, I don't really know what you'd get, hence the indexing might suffer.
Loading time is quicker with server side templating
Especially for mobile with low end phones, client side templating might make a noticeable difference. Especially if you have to fetch the data in a second step after page load. Ajax + rendering on these small devices adds a small delay. On server side with caching on the other side, you're pretty swift.
That said, despite all disadvantages, client side templating has its purpose
Client side templating rules with interactivity and two way data bindings
Typically for RIA (rich internet applications) where you read/edit/browse data in a very interactive fashion, client side templating can be very handy. It becomes a single page app, where the page is stateful and the adequate portions of the page is updated with corresponding data. The downside is of course that such sites are harder to develop, maintain and more error-prone.
For interactive and complex user interfaces it makes sense to leverage the browser for template rendering. However in your case, it's sounds that your page is pretty static, so it boils down to your preference of spending more time coding server-side, or client-side?
Take note that rendering content in the client-side has SEO implications. There are solutions and techniques to overcome this, but make sure you're aware of the effect of dynamically generated content and search-engines.
When rendering on the client-side, if you're requesting the template and the JSON, that's two extra HTTP requests and that will definitely slow down the user experience. However you can preload the template and even the JSON in the initial page-load from the server and make things much faster, for example:
<?php
$data = [ 'title': 'foo', 'content': 'lorem' ];
?>
<script id="tplArticle" type="text/template">
<h1>{{title}}</h1>
<p>{{content}}</p>
</script>
<div id="main"></div>
<script>
var data = <?php echp json_encode($data) ?>
var template = $('#tplArticle').html();
var html = Mustache.to_html(template, data);
$('#main').html(html);
</script>
This is a rough example of a PHP file that outputs the template and JSON on the first page-load from the server, and Javascript rendering the data and template on client-side without any extra HTTP request.

How should one initialize a page in backbone.js, to minimize HTTP requests and latency

I am learning about backbone, and from the examples and tutorials I have gotten this impression:
The initial GET / returns the skeleton page with backbone and the view templates.
Backbone uses the REST API to flesh out the page by GETting the data it needs and adding it into the DOM.
This works, but it seems wasteful in terms of additional HTTP requests, and latency from the perspective of the end user (minimum two round-trips before the page is visible. Actually three in my case, since the API must first ask which widgets are available, and then fetch the details on any available widgets....).
Is there an established, standard method for getting around this? My current candidates are:
Ignore the problem.
Embed the initialization data directly into the original page via inline javascript.
Render the page as if backbone didn't exist. When backbone finishes initializing, it will (hopefully) be in sync with the page as the user sees it. It can correct anything it needs to if things changed in the intervening couple seconds, but at least the user is not left hanging.
Another solution I haven't thought of?
Is there an established way to do this? Is it situation-specific? I am using Node / JS / Express.
Update: I think I found a solution, possibly the "accepted" solution, in Backbone's documentation:
Here's an example using reset to bootstrap a collection during initial page load, in a Rails application.
<script>
var Accounts = new Backbone.Collection;
Accounts.reset(<%= #accounts.to_json %>);
</script>
Calling collection.reset() without passing any models as arguments will empty the entire collection.

Node.js+Socket.io: Templating # server or browser? Load content via ajax or socket.io?

I already asked a similar question but this one is a bit different/specific:
I'm about to start development of a social community site (for a local user group) with features like timeline, IM/chat, forums, ...
Node.js and socket.io (or now.js) on the backend. jQuery (and maybe backbone.js or similar) on the front end. Content is loaded via socket.io or ajax and navigation via url hash.
There are 2 things where I just can't decide which way to go. I hope here are some people who can provide some good or bad experience.
Templating on server or in browser? I'm not sure if it's better to load a complete html site + live updates (also in html) for timeline, forum posts, IM/chat, ... or use something like a REST api via ajax or socket.io and do the templating on the client site. I've never done that before. You need to download the templates, etc, etc. Has anyone experience in this? There are also 2 ways to implement a rest-like api: E.g. request a forum post, then request the user associated to that post and so on (just like server side MVC) - or - request a forum post and the server answers with all needed information.
Load content via ajax or socket.io? I'm definitively using socket.io or now.js for real-time communication (IM, chat) and pubsub (on mainpage -> subscribe to new timeline updates, on a forum topic -> subscribe to new posts). But should I also load HTML (or provide a REST-like API, see question 1) through the socket? When people open forum posts in tabs (which I usually do a lot) that would mean a lot of socket connections. And I'm not sure how long it takes for a websocket to establish connection.
So there a 4 ways to do this:
HTML via AJAX - probably the most stable way that doesn't need a lot javascript to do the templating - Browser can use open HTTP connections to request stuff.
HTML via socket.io - The websocket must be established to load content (may be slower)
API via AJAX - as it probably needs more requests as HTML via AJAX there might be some HTTP header overhead + you need to authentication in each request- I'm not a friend of too many ajax requests.
API via socket.io - Socket must only be authenticated only once and you can request API objects on the fly. However I would still load templates and js via HTTP for browser caching.
I know this is a huge post but I'm debating for many days now and just can't decide as it would be a lot of work to switch the system once started developing. This is not a public project, it's limited to ~10k-15k local people and thus must not be that perfect, a good opportunity to learn new things in my opinion (I'm completely new to node, classic PHP MVC + jquery dev here).
I think you should use a RESTful api on the backend, let the templating occur just on the frontend (maybe with Backbone) and only use Socket.IO for real realtime stuff (such as chat). It doesn't make any sense to use websockets for something like loading HTML, because it most likely never changes.
So my vote is:
1) HTML via AJAX
2) API via AJAX
3) Realtime communication, such as chat messaging (or other stuff that constantly changes) via Socket.IO
Though there really isn't a definitive answer, as it depends.
If you need to be search engine crawlable, you can NOT rely only on client-side processing. If your individual views are light, and/or you need to support mobile, you should have initial rendering server-side.
Currently, I would suggest using an API that both your client application and server-side can use. If you use node for the server-side rendering you can re-use a lot of the same logic, including the API client.
Going a few steps farther, if you look starting with the Yahoo flux examples project on github, you can use the same logic both client and server-side including rendering with React views. This is not an easy solution, and will take some work.
For interactive elements, server-side rendering can be minimal with your stores pushing an event wiring up via sockjs/socket.io when the client starts for your chat/im bits.
You will have scalability issues when it comes to running across multiple processes and will likely need a pub/sub chain backed by a db for longer re-connect cycles or missed IM messages. There isn't a magic bullet.
Right now, I like flux+react... When Angular2 comes out, it may have a better story for server-side rendering.

Resources