So I'm trying to create a website that almost runs only on the clientside using symfony2, backbonejs and underscore.
symfony2 for the backend and backbonejs for the frontend.
Symfony2 uses twig templates which get compilled into php classes by the server.
Would it save server performance to avoid twig templates as often as possible and use javascript templates (underscore) instead?
Or doesn't it make a difference since the templates need to be fetched from the server anyway?
Fetching a static file from the server is always going to give you better server performance than having the server process a template and return the result. The chances of that being significant are pretty low though, and you'd have to benchmark it to find out how much difference it makes.
Fetching a static template file from a server and fetching a dynamically generated data file to inject into it may or may not give you better performance then having the server insert the data into the template. You'd have to benchmark it.
Performance benefits of using client side templates almost always come from:
Having to fetch small data files from the server instead of HTML documents
Modifying page of an existing page instead of clearing it and loading a completely fresh one
The benefits do have to be weighed against the costs though (which are either the additional work to make the site continue to work if JS isn't available combined with the use of pushState and friends to have workable URLs or the fragility and search engine invisibility of a site completely dependant of JS)
Related
My PHP template looks like this:
$html=file_get_contents("/path/to/file.html");
$replace=array(
"{title}"=>"Title of my webpage",
"{other}"=>"Other information",
...
);
foreach(replace AS $search=>$replace){
$html=str_replace($search,$replace,$html);
}
echo $html;
I am considering switching to a javascript/ajax template system. The AJAX will fetch the $replace array in JSON format and then I'll use javascript to replace the HTML.
The page would then be a plain .html file and a loading screen would be shown until the ajax was complete.
Is there any real advantages to this or is the transition a waste of time?
A few of the reasons I think this will be beneficial:
Page will still load even if the Mysql or PHP services are down. If the ajax fails I can handle it with an error message.
Bot traffic (and anything else that doesnt run JS) will cause very little load to my server since the ajax will never be sent.
Please let me know what your thoughts are.
My 2cents is it is better to do the logic on the template side (javascript). If you have a high traffic site you can off load some of the processing to each computer calling the site. Maybe less servers.
With Javascript frameworks like AngularJs the template stuff is pretty simple and efficient. And the framework will do caching for you.
Yes, SEO can be an issue with certain sites. There at proxy tools you can put in place that will render the site and return the static html to the bot. Plus I think some bots render javascript these days.
Lastly, I like to template on the front-end because I like the backend to be a generic data provider (RESTful API). This way I can build a generic backend that drives web / mobile and other platforms in a generic way. The UI logic can be its separate thing in javascript.
But it comes down to the design needs of your application. I build lots of Software as a service applications so a single page application works well for me.
I've worked with similar design pattern in other projects. There are several ways to do this and the task would involve managing multiple project or application modules. I am assume you are working with a team of developers and not using either PHP or JavaScript MVC framework.
PHP Template
For many reasons, I'm against using “search and replace” method especially using server-side scripting language to parse HTML documents as a templating kit.
Why?
As you maintain business rules and project becomes larger, you will
find yourself reading through a long list of regular expressions,
parse HTML into DOM, and/or complicated algorithms for searching
nodes to replace with correct text(s).
If you had a placeholder, such as {title}, that would help the
script to have fewer search and replace expressions but the design
pattern could lead to messy sharing with multiple developers.
It is ok to parse one or two HTML files to manage the output but not
the entire template. The network response could be slower with
multiple and repetitive trips to server and that's just only for
template. There could be other scripts that is also making trips to
the server for different reason unrelated to template.
AJAX/JavaScript
Initially, AJAX with JavaScript might sound like a neat idea but I'm still not convinced.
Why?
You can't assume web browser is JavaScript-enabled in every mobile
or desktop. You might need to structure the HTML template in few
ways to manage the output for non-JavaScript browsers. You might
need to include <noscript> and/or <iframe> tags on every page. And,
managing alternative template for non-JavaScript browser can be
tedious.
Every web browser interpret JavaScript differently. Most developers
should know few differences between IE, FireFox, Chrome, Safari, and
to name few. You might need to create multiple JavaScript files to
detect then load JavaScript for that specific web browser. You
update one feature, you have to update script for all web browsers.
JavaScript is visible in page source. I wouldn't want to display
confidential JavaScript functions that might include credentials,
leak sensitive data about web services, and/or SQL queries. The idea
is to secure your page as much as possible.
I'm not saying both are impossible. You could still do either PHP or JavaScript for templating.
However, my “ideal” web structure should consist of a reliable MVC like Zend, Spring, or Magnolia. Those MVC framework include many useful features such as web services, data mapping, and templating kits. Granted, it's difficult for beginners with configuration requirements to integrate MVC into your project. But in the end, you could delegate tasks in configurations, MVC concepts, custom SQL queries, and test cases to developers. That's my two cents.
I think the most important aspects you forgot are:
SEO : What about search engine bots ? They wont be able to index your content if it is set by javascript only.
Execution and Network Latency : When your service is working, the browser will wait until the page is loaded (let's say 800ms) before making the extra Ajax calls to get your values. This might add an extra 500ms to get it (depending on network speed and geographic location...). If you have sent all the generated data by your server, you would have spent only ~1ms more to prepare the complete response. You would have a lot of waiting on a blank page.
Caching : You could cache the generated pages on your web app. That way your load will be minimized as well. And also, if you still want to deliver content while your backend services (MySQL/PHP..) are down you could even use Apache or Nginx caching.
But I guess it really depends on what you want to do.
For fast and simple pages, which seems to be your case, stick with backend enhancements.
For a dynamic/interactive app which can afford loading times, and doesn't care about SEO, you can delegate most things to the front-end. But then use an advanced framework like Angular, to handle templating, caching, etc...
I have a site written in Asp.net webforms. It uses ajax heavily.
Most forms on the site are submited with javascript. Javascript validates the input and sends it to /ajax.ashx on the server. The server processes the request and sends back a JSON response. My javascript uses the JSON to create html, which it inserts into the Dom.
I'm making a new version of my website written using asp.net MVC3. I've been looking at tutorials on this subject, and some of them recommend doing ajax in a different way. Rather than sending data and then building + inserting html with javascript, they create html at the server, and use javascript only to insert it into the Dom. For instance, in this tutorial.
Which way should I use? Using the new method will be quicker, but is it better?
That's a subjective question. Both approaches are possible and there is no better way. There are pros and cons of each approach.
Building the HTML on the server is easier and will require you less efforts but consumes more bandwidth compared to the first approach.
If you decide to go the first way you could use some client side templating framework which might help you simplify the generation of DOM elements on the client.
Creating html code directly into the server and injecting it with an ajax call is very fast and simple, the real problem is that in that way your service is bound to be used with that specific application. By sending RAW data you allow any app to use that data in any way, without bounding it to a specific application.
returning json feels more flexible to me; you can change what happens with your json response, like the layout it results in. If you return html you return data mixed with layout. This doesn't feel right to me.
I believe it is better to separate the layout from the actual data. That is why you should pass data between your scripts and not HTML.
If you go about it sending HTML, consider that you would have to build valid HTML and CSS, which might not sound hard at first but then you'll start using CSS that is not loaded in the file calling the ajax, etc.
Always separate content (data) from layout. That's why there is HTML and CSS, to separate layout from data. So why mess things up by mingling HTML between data?
Building the html serverside will probably be faster and not bog down the client which is important. Rendering data into HTML with javascript takes time and not every browser is fast with js (i.e. older versions of IE) so things can slow down if you're doing a lot of this.
Like previous posters said, it's kinda subjective because it depends on how much you're offloading to the client. I'm of the opinion that if you can do things serverside, you should.
If you are going to be using this service to return JSON to other applications/clients, then it's probably a good idea to just leave it as JSON and let the client do what it needs on their side.
I recent came across Javascript templates and have become quite intrigued.
I am building a large PHP application using the MVC pattern. Templating is handled by the rather awesome Twig.
I recently came across a javascript implementation of twig.
I have also read quite a bit about using javascipt template engines.
Now, in my application, the application generates a the full page for standard requests as fallback for users without javascript. For AJAX requests, it can generate the content part of the page (no <head>, <body> etc).
The ajax response object is currently just a the rendered HTML content, which is then inserted into DOM.
Should I instead return a response object containing a compiled javascript template and the objects to be inserted into the template? What are the benefits of doing that?
From the posts I have read, the javascript templates were only small snippets representing a small part of a page, for example displaying a comment on a blog post during the instant that the user has submitted it.
Are javascript templates only useful for inserting these sort of small "pieces" in a page?
Yes
A recent project I was on got "client-side template fever" and we used the dang things for every single template.
With every template library I've used (which is two or three), the error messages you get are not very good. If you have a huge template that operates on a fair amount of data, you'll quickly find the u.foo is null or not an object error message increasingly frustrating.
The best-practices I've settled on is:
Return a full HTML snippet (from the server) if it's a template that is seldom loaded. If you are only loading that HTML once on a page, then you might as well send it down populated right? This also encourages you to keep your logic up on the server, where it probably belongs.
Use client-side templates for small, repeated templates. Your blog comment example is probably a good one. I've found the most success when my client-side templates are pretty small (< 10 lines)
Use a logic-less template engine. The more logic allowable in a template, the harder they are to read/maintain. Plus, some of that logic should probably be in your business layer, not down in some JavaScript template. In other words, they force you to separate your presentation from your logic (which is good).
PS: It is cool that both your client and server-side templates could use the same templating engine. This will make developers on your project much more productive.
Depending on the scale and requirements of your application, you should take into considerations the following:
don't go rampant on Ajax; Ajax is not WebSockets, so use it sparingly. Plus, client-side execution speed is always key; AJAX is slow when compared to dumping as much resources as possible + using them when you need them; for example, you can send to javascript userdata = {name:'xxxx',address;'yyyy', ...} and using that, instead of requesting name and address via AJAX only when you need them.
it is recommended to use a global PHP var $sendData (or something like that) and right after plasting HTML, you send the $sendData with an easy <script>data = <?php echo json_encode($sendData); ?></script>
javascript templates add up to execution speed. which makes it reasonable to do the alternative, that is, separating everything that is dynamic and caching static resources like javascript functions
you can't, and I quote return a response object containing a compiled javascript template, not without residing to some server-side javascript engine that does the compile job prior to returning it
for your personal welfare, it will always boil down to how fast, easy and painlessly you respond to maintaining the application; there's no point in using super beta experimental frameworks, ports and kits over which you have limited control
Work smart, not hard.
Good luck mate.
You could also look into the Distal http://code.google.com/p/distal templating engine.
I have been trying to learn Node.js for a few days now, but there is one thing I am confused about.
What is the difference between a client-side templating solution like JQuery templates and a server-side solution like Jade for Node.js?
What are the uses for each? Where are they used? Can they be used together? Is there an exampe of both of them being used together if so?
I just can't get my head around this. Would be nice to have an overview of things from somebody around here...
The biggest thing that should be considered about client-side vs server-side templating is that client-side templating will not work if JavaScript is disabled on the client for whatever reasons.
Otherwise it's not such a big difference. It's mostly up to whether you want to generate your markup on the server, or on the client.
A typical reason to use client-side templates is if you have an application which loads more data from the server using ajax, websockets or such. In such a case you might want to have a client-side template for rendering the newly loaded data.
For example:
In an application I wrote, I used ejs templates on server to generate the basic markup: The head, body, footer, etc. - content which doesn't change.
The application uses socket.io, which sends the client some events and data from the server. To display this data, I used Knockoutjs' client-side templating.
So in my case it's kind of a hybrid approach. The reason I did it like this is because the markup I generate on the server will immediately show once the page loads. The data which comes from socket.io could have also been rendered into HTML on the server, but that would require more bandwidth to send than sending simple JSON objects or such, so I opted to render them on the client.
Obviously I could have used a client-side template for the entire site, but I saw no benefit in rendering the static parts on the client. It would have just made the client-side code of my application more complicated.
I'm building a Django web application which has a lot of html generated on the fly by ajax requests. Right now I use Django's templating language to build up html and then pass this new HTML as a string in JSON object which is then injected into the page with jQuery.
This works fairly well, but with Javascript being so fast in modern browsers and with so many javascript template libraries being made I'm wondering if I should push everything clientside.
So my question is: Given the that my average "page" with all requests to and from it has to compile around ~300 templates (each of about 15 or so lines with 5 or so substitutions) out into HTML during its lifetime is there significant performance advantage to doing templating in the browser?
In addition can anybody reccomend a 'fast' Javascript templating library? I've heard good things about underscore.js, mustache.js and jQuery template.
The (massive) advantage of sticking with Django templates is that you only need to use one templating language, which retains the same capabilities regardless of the page you wish to generate. If you find that you're having performance issues then you should consider looking into caching template fragments.
I don't think an hybrid client and server templating architecture is bad. As long as you code a template only in one of the environment.
Every time you generate a page server side, an amount of processing time and some network bandwidth is consumed. This is what you pay if you use hosted servers.
While the user's browser is awaiting idle on a generally idle computer for the response.
If you send the template on the client(HTML + JS), they can be cached, for the session or even days, if the user do not delete them.This reduces the network traffic to deliver the same content various times. As the data are generally smaller than their equivalent rendered HTML.
As you point today's Javascript engines are really fast, as well as the computer they run it. Each time you sent the rendering work to the client, you save some processing time for your server and deliver faster the data.
We're at the other extreme side, as we run all on the client and that's why we created PURE for an ultra-fast client rendering. Our app looks very fast as a result of this decentralisation.
Why do you pass the HTML as JSON? Just send back the HTML and use jQuery's $.html() function to put it in the <div> or whatever.
As for templating in Javascript, there's Pure. If you're using jQuery (I'd recommend it), it already has a template engine.
It may be possible to make templates of dual purpose - to that they could be rendered into placeholders for the replacement by js and at the same time they could be rendered normally for the server output. Only a few templates will need to be of dual purpose like that - the fragments that are to be replaced by the js.
I agree with Ignacio, it is much better to keep just one copy of each template, so that you don't have to write a separate one for the javascript, however there is definitely room for improvement from the approach that I've mentioned above.
Ideally you might want to have templates compiled into robust javascript function code as well as plain string for the output by the server.
Closure templates called Soy, solve the problem nicely but do not (perhaps just yet) work with python, but they do work with Java and Javascript. Hopefully one day there will be python support for that.
But even if that happens, the templating language will be probably more restricted as it will be tough to make things like .get_absolute_url(), filters, etc work both in python and javascript - all automatically.