patternjavascriptMinor
Converting a Website Into a Single Page App
Viewed 0 times
websiteappintosinglepageconverting
Problem
I want to convert my website into a single page app. This function does the trick:
Assuming I have no redirects other than `` tags, it should work fine, right? It feels so wrong and yet so right...
$(document).ready(function(){
$("body").delegate("a", "click", function(){
var href = $(this).attr("href");
$.get(href,function(data){
var newDoc = document.open("text/html", "replace");
newDoc.write(data);
newDoc.close();
});
return false;
});
});Assuming I have no redirects other than `` tags, it should work fine, right? It feels so wrong and yet so right...
Solution
It will work, but consider why you might be doing SPA's:
With your approach,
Furthermore, you run the risk of memory leaks, which happen like this:
- No more full screen flickering, better user experience
- Keep your state on the browser side instead of pingponging it between server & browser
- Less network traffic if you only request for data & do the rendering with templates in JS
With your approach,
- You are rebuilding the whole DOM from scratch everytime, so there will still be flickering.
- With script tags being replaced while JS is still running, I dont even want to think about what mess your state will be in ;)
- You are still fetching data + layout from the server, so not gaining anything from a network perspective.
Furthermore, you run the risk of memory leaks, which happen like this:
- Add any listener to your DOM
- Forget to unbind that listener when the user clicks a link
- New content is loaded, old DOM is gone, but that old listener is still out there
Context
StackExchange Code Review Q#136601, answer score: 3
Revisions (0)
No revisions yet.