Creating new html in JS or ajax loading a html layout?

By : Jourkey

I have a page where I need to create a large amount of HTML that's not already present in the page.

Using jQuery I've been building the page with JS piece by piece, adding divs here and there, etc, until I get my layout.

Right now I'm thinking rather than do all that in JS, I can create the layout in a separate HTML file and then load it with ajax. My initial aversion to that idea is because of ajax, it requires an additional server request, and might end up slow(er?).

Anyone have any advice on whether or not this is a good idea, and if it is, if there are tutorials, set ways and patterns to doing this sort of thing.


By : Jourkey


The issue you'll get is not slower, but your URLs will be a little messed up.

If you navigate from page to page your URL won't update easily. You CAN do it but it can be a lot of work.

I've used post's callback function to display the data from the post with good effect and it's fast.

Good luck with it!

edit: I was talking about jQuery's post function.

2nd edit: If you're going to vote me down guys, at least say why...

By : Dorjan

There may be a speed impact from making another round-trip to the server. However, I think that the readability/maintainability you gain from having all of your HTML in a separate template, rather than mixed in with your JS is the big win here. You won't have to deal with quote issues, entity encoding, all of that. And the code that you do have will be easier to debug.

I'm not aware of any specific tutorials on this, but with most of the AJAX libraries out there, it's easy to make an XHR request and pipe the response into a DIV. For example, see Prototype's Ajax.Updater(container, url[, options]) function. ( )

This video can help you solving your question :)
By: admin