How does StackOverflow provide a preview of markdown text, without causing lag?


I'm making a blog that takes markdown syntax. I would like to be able to provide an updated preview on every keystroke, just like Stackoverflow does when asking and answering questions. My current solution is incredibly laggy.

How does Stackoverflow implement their solution to provide an updated preview of markdown text without causing lag?

Currently, I make an AJAX call to the server on every keystroke in the post-content text area. The server sanitizes the content and returns HTML. The preview div is then updated with the new HTML:

$('#post-content').bind('input propertychange', (function() {
    var content = {"content": this.value};
        success: function(data) {

This isn't working well. If I type at full speed, the text area ends up missing about 1/3 of my characters. My server is a tiny 500MB RAM VM. I'm not sure if the server is bottle neck, but I don't understand why the textarea would be lagging because of a slow AJAX call - it seems to me that this line is the bottle neck:


But I don't know enough about front end development to speculate on this.


Stack Overflow renders the preview client-side, which is why some of the tags aren't sanitized. AJAX calls (especially lots of them) are not neccesary, because most computers can do it just as easily without the server's help.

If you notice, syntax highlighting is not triggered for a few seconds, because it is inefficient to do that every time a character is typed.

By : RamenChef

Don't send an AJAX call at every keystroke to the server! Make the preview use something client-side and only use the server when you submit the post/comment.

By : Bálint

Creating the AJAX call is what is causing your lag. I haven't exactly looked but I can promise you that StackOverflow is not making a server call each time to validate and give you a preview of the markdown. They are just using Javascript to do it instead.

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