We have pretty standard web-site and I got a task to convert links between pages to AJAX calls, but maintain direct links (from search engines, for example) working too.
My goals:
- Leave direct links working as before (and hash fallback for old IE), smooth transition from arriving by direct link and futher browsing using AJAX
- Implement some “garbage collection” (DOM of previously viewed pages, script handlers etc)
I’ve seen something similar in jQuery Mobile, but I’m looking for more general solution to get inspiration (or borrow code) from 🙂
Ok well first you need to be able to separate external and internal links. I wrote the following JQuery selectors for that purpose:
This lets you select all internal or external links
$("a:internal")....Next you need to override the click event on all internal links, override the default behaviour grab the Href url and perform an ajax request to the href URL and spit the result into the body
You’ll also need to look at history.js for enabling browser history/back button and address bar updates. You’ll also need to detect AJAX requests on the serverside and return only the
<body>or else return everything and change the example above to$("html").html(data).You’ll need to handle the onLoad/DOM events or use the new JQuery “On” Handler
$(document).on("click", "a", ajaxLinkHandler)That way when the click event bubbles up to the document it will check if it was initiated from an anchor tag, therefore no onReady event required.The browser manages DOM garbage collection for you. Open any JQuery page, go to the firebug/chrome dev tool DOM tab and inspect the document. Then go to the console tab and type $(“html”).remove() go back to the DOM tab and you’ll see its been totally cleaned up. You’re calling replace() not remove, so the old DOM elements are replace with the new ones from the AJAX call.