312

It is quite easy to load HTML content from your custom URLs/Web services using JQuery or any other similar framework. I've used this approach many times and till now and found the performance satisfactory.

But all the books, all the experts are trying to get me to use JSON instead of generated HTML. How's it much more superior than HTML?

Is it very much faster?
Does it have a very much lesser load on the server?

On the other side I have some reasons for using generated HTML.

  1. It's simple markup, and often just as compact or actually more compact than JSON.
  2. It's less error prone cause all you're getting is markup, and no code.
  3. It will be faster to program in most cases cause you won't have to write code separately for the client end.

Which side are you on and why?

Cyril Gupta
  • 13,505
  • 11
  • 64
  • 87
  • 1
    it's worth noting that the X in AJAX is XML, and HTML at one point was supposed to be XML. The idea was that HTML was human and machine readable data (like JSON), and CSS would do the presentation. Under those conditions, it would not violate "separation of concerns" to send HTML in an AJAX request – code_monk May 07 '17 at 13:07
  • 1
    To add to the conversation 13 years later for the Googlers...Building dynamic HTML server-side can be a bit easier and safer. For example, returning a page or partial in ASP.NET built by Razor means that your HTML template was actually compiled and attached to a strongly-typed model. Less possibility for misspellings/typos, wrong variable name case, invalid nesting, malformed HTML, etc. - all issues that you might run across if you're using a client-side template, and might potentially not notice right away. – Joe Enos Oct 13 '22 at 23:45

14 Answers14

264

I'm a bit on both sides, actually :

  • When what I need on the javascript side is data, I use JSON
  • When what I need on the javascript side is presentation on which I will not do any calculation, I generally use HTML

The main advantage of using HTML is when you want to replace a full portion of your page with what comes back from the Ajax request :

  • Re-building a portion of page in JS is (quite) hard
  • You probably already have some templating engine on the server side, that was used to generate the page in the first place... Why not reuse it ?

I generally don't really take into consideration the "performance" side of things, at least on the server :

  • On the server, generating a portion of HTML or some JSON won't probably make that much of a difference
  • About the size of the stuff that goes through the network : well, you probably don't use hundreds of KB of data/html... Using gzip on whatever you are transferring is what's going to make the biggest difference (not choosing between HTML and JSON)
  • One thing that could be taken into consideration, though, is what resources you'll need on the client to recreate the HTML (or the DOM structure) from the JSON data... compare that to pushing a portion of HTML into the page ;-)

Finally, one thing that definitly matters :

  • How long will it take you to develop a new system that will send data as JSON + code the JS required to inject it as HTML into the page ?
  • How long will it take to just return HTML ? And how long if you can re-use some of your already existing server-side code ?


And to answer another answer : if you need to update more than one portion of the page, there is still the solution/hack of sending all those parts inside one big string that groups several HTML portions, and extract the relevant parts in JS.

For instance, you could return some string that looks like this :

<!-- MARKER_BEGIN_PART1 -->
here goes the html
code for part 1
<!-- MARKER_END_PART1 -->
<!-- MARKER_BEGIN_PART2 -->
here goes the html
code for part 2
<!-- MARKER_END_PART2 -->
<!-- MARKER_BEGIN_PART3 -->
here goes the json data
that will be used to build part 3
from the JS code
<!-- MARKER_END_PART3 -->

That doesn't look really good, but it's definitly useful (I've used it quite a couple of times, mostly when the HTML data were too big to be encapsulated into JSON) : you are sending HTML for the portions of the page that need presentation, and you are sending JSON for the situation you need data...

... And to extract those, the JS substring method will do the trick, I suppose ;-)

Pascal MARTIN
  • 395,085
  • 80
  • 655
  • 663
  • 6
    All data is ultimately presentation. – Cyril Gupta Aug 17 '09 at 05:39
  • 49
    @Cyril: Huh? I think you are trying to say that data, to be useful, has to be used and thus presented somewhere in some form, and I agree. But to say that data **is** presentation seems misguided, at the very least. – Vinko Vrsalovic Aug 17 '09 at 13:45
  • 10
    Hi Vinko, notice the 'ultimately'? I mean exactly what you mean. Just trying to get into the book of quotable quotes here. Ha ha! – Cyril Gupta Aug 17 '09 at 14:45
  • Still, I got your meaning but I disagree with the phrase in this context. Data to be useful has to be presented, but that doesn't mean that JSON and HTML are equivalent because, in the end they are both data (or presentation?). – Vinko Vrsalovic Aug 18 '09 at 00:58
  • 37
    The basic question is whether you are absolutely, positively, ultimately sure you will not be using this data for anything but HTML. Because once packed into HTML, the data will be nearly unrecoverable. With JSON your backend can work with XML, SVG, database engines, cross-site API and a thousand other frontends and systems that can accept JSON. With HTML, you will be only able to use it in within HTML. – SF. Mar 11 '10 at 15:43
  • 3
    @SF: When returning HTML from the server, I make sure to split the HTML generating code from the code that accesses the database. That way I can easily add a JSON form as well. – Casebash Jun 22 '10 at 05:48
  • @pascalmart, may I request you to have a look at a jquery question on a different topic here : http://stackoverflow.com/questions/13137404/jquery-find-div-class-name-at-a-certain-position-while-scrolling ? – Istiaque Ahmed Oct 31 '12 at 07:47
  • 2
    @PascalMARTIN Why was this question accepted? Doing all of the HTML rendering on the server doesn't scale nearly as well as building the views on the client (unless you only ever plan to build small sites). On top of that, concatenating partial views on some pseudo domain-specific language and extracting them using substring on the client? You just created a crappier version (of the already pretty crappy) PHP for the client. You earned a ::facepalm:: from me on this one. – Evan Plaice Nov 08 '12 at 00:25
  • @VinkoVrsalovic Here, if HTML data it is presentation. yes it is data, but with presentation. Jason can never be used directly without binding it with HTML. – MarmiK Mar 25 '13 at 10:30
  • 1
    Most answers debate on performance. **You must not forget security.** I was all happy working on my latest project, building HTML on the client based on JSON returned via AJAX. Suddenly I looked at my JSON on FireBug and went "damn! I am showing too much data infrastructure"! So, I am rewriting my code to have the server return HTML. I think from know on I'll go with Pascal MARTIN: - HTML for presentation - JSON for non-compromising data – Alexandre Paulo Mar 07 '14 at 19:31
  • 2
    "Re-building a portion of page in JS is (quite) hard" Is this still true today? Don't we have client side templating engines for this now? – jpmc26 Mar 15 '17 at 05:19
  • The self-contained systems architecture (just came across) might serve good arguments for delivering HTML, see https://scs-architecture.org/index.html and roca-style.org – chriscross Feb 27 '19 at 02:00
123

I mainly agree with the opinions stated here. I just wanted to summarize them as:

  • It is bad practice to send HTML if you end up parsing it client-side to do some calculations over it.

  • It is bad practice to send JSON if all you'll end up doing is to incorporate it into the page's DOM tree.

Vinko Vrsalovic
  • 330,807
  • 53
  • 334
  • 373
  • 4
    what if you need to do some calculations and also incorporate it to the page's DOM? – Enrique Feb 01 '12 at 02:56
  • I wonder how long will the above statement have a truthfulness attached to it, If you add the "[Half-life of Knowledge](http://en.wikipedia.org/wiki/Half-life_of_knowledge)" into equation? – Val Jul 02 '14 at 09:44
  • is it possible to return an HTML that has – nish1013 Apr 13 '16 at 10:00
  • This. Also if you are returning data that needs to be fluid in its presentation in some way, e.g. if you have an HTML table with columns that you would like to be able to sort. Whether you HAVE made them sortable now or not, you might want to later, so in such a case, the future-proofing is worth the extra effort of going the JSON route. – trpt4him Jul 25 '16 at 18:47
  • I would also add, if you are requesting image urls via JSON just to try to render them on the page, it's far more performant to include them in HTML from the start, so that images can start loading earlier (before your ajax comes back). – FailedUnitTest May 15 '19 at 12:18
33

Well,

I'm one of those rare persons that likes to separate things this way: - The server is responsible for delivering data (model); - The client is responsible for showing (view) and manipulating data (model);

So, the server should focus on delivering the model (in this case JSON is better). This way, you get a flexible approach. If you want to change the view of your model, you keep the server sending the same data and just change the client, javascript components, that change that data into a view. Imagine, you have a server delivering data to mobile devices as well as desktop apps.

Also, this approach increases productivity, since the server and client code can be built at the same time, never losing the focus which is what happens when you keep switching from js to PHP / JAVA / etc.

Generally, I think most people prefer to do as much as possible on the server side because they don't master js, so they try to avoid it as much as possible.

Basically, I have the same opinion as those guys that are working on Angular. In my opinion that is the future of web apps.

mrid
  • 5,782
  • 5
  • 28
  • 71
ramaralo
  • 1,013
  • 2
  • 10
  • 15
  • Yes I totally agree with you. However doing as much server side when sensitive information is concerned I would deem best. If you need the client to react differently depending on the result I would use json otherwise I'd use html. – Fi Horan Sep 14 '16 at 14:30
  • Now it is 2021 and yes, everybody is switching to or at least following news about these new JS frameworks (Svelte/Vue/React/etc). Nice prediction ;) – Ulvi Mar 13 '21 at 15:10
9

I have something interesting I thought I might add. I developed an application that only ever loaded a full view one time. From that point forward it communicated back to the server with ajax only. It only ever needed to load one page (my reason for this is unimportant here). The interesting part comes in that I had a special need to return some data to be operated on in the javascript AND a partial view to be displayed. I could have split this up into two calls to two separate action methods but I decided to go with something a little more fun.

Check it out:

public JsonResult MyJsonObject(string someData)
{
     return Json(new { SomeData = someData, PartialView = RenderPartialViewToString("JsonPartialView", null) }, JsonRequestBehavior.AllowGet);
}

What is RenderPartialViewToString() you might ask? It is this little nugget of coolness right here:

protected string RenderPartialViewToString(string viewName, object model)
{
     ViewData.Model = model;

     using (StringWriter sw = new StringWriter())
     {
          ViewEngineResult viewResult = ViewEngines.Engines.FindPartialView(ControllerContext, viewName);
          ViewContext viewContext = new ViewContext(ControllerContext, viewResult.View, ViewData, TempData, sw);
          viewResult.View.Render(viewContext, sw);

          return sw.GetStringBuilder().ToString();
     }
}

I haven't done any performance testing on this so I'm not sure if it incurs any more or less overhead than calling one action method for the JsonResult and one for the ParticalViewResult, but I still thought it was pretty cool. It just serializes a partial view into a string and sends it along with the Json as one of it's parameters. I then use JQuery to take that parameter and slap it into it's appropriate DOM node :)

Let me know what you think of my hybrid!

CatDadCode
  • 58,507
  • 61
  • 212
  • 318
  • 1
    Sending the rendered view and the data in one request seems a little redundant redundant. Just kidding, if you had the ability to do client-side view rendering it would be even better to send the view template and data as separate requests. It required an additional request but only once as the template request will be cached for subsequent requests. Ideally it would be best to use a combination of client and server-side view rendering so you can build pages on the server and partials in the browser but if you only implement server-side view rendering, this isn't a bad approach. – Evan Plaice Nov 08 '12 at 00:34
8

If the response needs no further client-side processing, HTML is OK in my opinion. Sending JSON will only force you to do that client-side processing.

On the other hand, I use JSON when I don't want to use all the response data at once. For example, I have a series of three chained selects, where the selected value of one determines which values are going to be used for populating the second, and so on.

Ionuț G. Stan
  • 176,118
  • 18
  • 189
  • 202
7

IMV, it's all about separating the data from the presentation of the data, but I'm with Pascal, it doesn't necessarily follow that that separation can only be across the client/server boundary. If you have that separation already (on the server) and just want to show something to the client, whether you send back JSON and post-process it on the client, or just send back HTML, depends entirely on your needs. To say you're "wrong" to send back HTML in the general case is just far too blanket a statement IMV.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
6

If you want a clean decoupled client, which in my opinion is best practice, then it makes sense to have 100% of the DOM created by javascript. If you build an MVC based client that has all the know how to build the UI then your users download one javascript file one time and it's cached on the client. All requests after that initial load are Ajax based and only return data. This approach is the cleanest I have found and provides for a clean independent encapsulation of the presentation.

The server side then just focuses on delivering data.

So tomorrow when product asks you to change the design of a page completely all you change is the source JS that creates the DOM, but likely get to reuse your already existing event handlers and the server is oblivious because it 100% decoupled from presentation

Lance Caraccioli
  • 1,421
  • 13
  • 14
  • 1
    I agree, also you can reuse the json for your mobile app. – Alex Shilman Aug 29 '14 at 18:22
  • This should have been the accepted answer - the first 6 - 7 words answer the question succinctly. – nicholaswmin Oct 02 '17 at 04:50
  • Agree. The advantage of return data (JSON) over presentation(html) is that you now have a "free" web API which can be re-used for other clients be it mobile or a completely different app that is interested in some data from this app etc. In my experience using a simple web framework on server side that only deals with data and not presentation often leads to good and simple results. Modern browser and CPUs are so fast that only in special cases the rendering will be a bottleneck . The biggest bottleneck mostly being the network itself and the database call. – beginner_ Jun 29 '18 at 06:50
6

JSON is very versatil and lightweight format. I have discovered its beauty when I have started to use it as a client side template parser data. Let me explain, while before I was using smarty and views on server side (generating high server load), now I use some custom jquery functions and all the data is rendered on client side, using clients browser as template parser. it saves server resourses and on another hand browsers improve their JS engines every day. So the speed of client parsing is not an important issue right now, even more, JSON objects are ususally very small so they don't consume a lot of client side resourses. I prefer to have a slow website for some users with slow browser rather than slow site for everyone because of very loaded server.

On another hand, sending pure data from server you abstract it from presentation so, if tomorrow you want to change it or integrate your data into another service you can do it much easier.

Just my 2 cents.

Mike
  • 654
  • 7
  • 18
  • And how do you ensure you get a readable page when javascript is disabled? – Vinko Vrsalovic Nov 30 '09 at 14:25
  • 8
    if JS is disabled you will not be able to load html as well. JS is disabled on 2.3% of users according to my Google Analytics stats. The best way to go down is to try to please everyone. – Mike Nov 30 '09 at 15:36
  • 4
    I agree 100% with Mike. Trying to please everyone is impossible and will only hurt you. If users are turning off JS then they must be used to many sites not working for them by now. – CatDadCode Nov 07 '10 at 07:17
  • 1
    How do you get JavaScript stats in Analytics since Analytics uses Javascript to track data? – Nick Feb 12 '14 at 19:34
  • @Nick Good question, but i found this: http://stackoverflow.com/questions/15265883/using-google-analytics-without-javascript – Renan C Jul 18 '16 at 03:18
4

Depending on your UI, you may need to update two (or more) different elements in your DOM. If your response is in HTML, are you going to parse that to figure out what goes where? Or you can just use a JSON hash.

You can even combine it, return a JSON w/ html data :)

{ 'dom_ele_1' : '<p>My HTML part 1</p>', 'dome_ele_2' : '<div>Your payment has been received</div>' }
tchen
  • 2,212
  • 1
  • 16
  • 18
  • It is bad practice to send JSON if all you'll end up doing is to incorporate it into the page's DOM tree... and by combining JSON with HTML you are using this bad pratice – thermz Mar 26 '12 at 14:02
2

HTML has many redundant and not displayed data i.e. tags, style sheets etc.. So HTML size compared to JSON data will be bigger leading to more download and render time also it will cause browser to be busy rendering the new data.

John Saman
  • 106
  • 1
  • 5
1

Sending json is generally done when you have a javascript widget requesting information from the server, such as a list or a tree view or an autocomplete. This is when I would send JSON as it is data that will be parsed and used raw. However if your just gonna show HTML then its a lot less work to generate it server side and just show it on the browser. Browsers are optimized for inserting HTML directly into the dom with innerHTML = "" so you can't go wrong with that.

Zoidberg
  • 10,137
  • 2
  • 31
  • 53
  • FWIW, `innerHTML` is historically much slower than a document fragment: https://coderwall.com/p/o9ws2g/why-you-should-always-append-dom-elements-using-documentfragments. – Nate Whittaker Jul 29 '16 at 18:06
0

Html response is enough in most of the cases unless you have to perform some calculation at the client side.

Mubashir
  • 567
  • 3
  • 8
  • 25
0

I think it depends on the structure of the design, it's just more sexy to use JSON than HTML but the question is how would one handle it so it can be easily to maintain.

For example, say I have the listing page that utilize the same html/style of the entire site, I would write the global function to format those portions of HTML and all I have to do is passing the JSON object into the function.

Methee
  • 116
  • 1
  • 6
0

Depends on the circumstances.

Sometimes it is essential to avoid JSON. When our programmers have trouble programming in js, for example.

My experience tells me that: better use ajax service than inline JSON.

Sooner or later the js becomes a problem

Alegoric
  • 1
  • 1