Ajax loading: Handling duplicate Ids with JQuery.

As single page web apps getting popular, there's often one problem: when a user goes to another page and goes back while all were done with ajax, some items will be left behind. 

This happens when an item gets created outside of the container that gets loaded, so JQuery's .html() would replace what was in the old container. However, sometimes because of some third party library you use, there may be appended elements that is outside of the tag or they may have moved some elements to the bottom of the page (i.e. JQuery UI's dialog boxes). This is really annoying because you will end up with duplicate items. So next time when you want to call up a specific item with certain ID, you will get the old one that will be hidden from the user.

The trick here is to tag every class that you inject with with a special class, say "injectedItem", now before you replace the old html with a new page, you call $(".injectedItem").remove() to remove all the proper elements. Note that you don't have to tag the elements that you are sure that will be removed properly under .html(). 

Ajax loading: No Hashbangs, just HTML5

Hashbangs (#!) has been around the web for a while now since Twitter started using it for Ajax page loads. I was rather annoyed by the unnecessary page refreshes from time to time. But noooow...Twitter is finally starting to move away from hashbangs! I remember talking to the front-end engineer at Twitter a few months ago at their San Francisco headquarter with it and asked them why they did it.  It was when I was working on the menu's for SleepBot. After I came back to New York, I wanted to implement it for SleepBot. However, it turned out that it is not that simple to parse out the URL's hashbang after all and press was there for us to release it on time.

So I ended up using History.js, a Javascript wrapper for HTML5 history management: on the links that uses ajax load, we bind the click with the following if statement:

if(History.enabled){
//Do the ajax load, and then use History.pushState(....) to update the url
}else{
//IE users, I'm sorry, you are getting a cold refresh. 
}

This worked at first, however, as the project grows, problem happens with Ajax load: bindings stopped working! It was caused by my lack of understanding for jQuery's bind live and delegate functions. If you are serious about web development using jQuery, that is a must read.