4
\$\begingroup\$

I want to convert my website into a single page app. This function does the trick:

$(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 <a> tags, it should work fine, right? It feels so wrong and yet so right...

\$\endgroup\$
  • \$\begingroup\$ Umm... Are you asking us to verify if the code is correct? \$\endgroup\$ – Pimgd Aug 2 '16 at 7:30
  • \$\begingroup\$ @Pimgd No, I know it will work, but is it poor practice? Are there better ways? \$\endgroup\$ – Jonah Aug 2 '16 at 8:16
  • 2
    \$\begingroup\$ @Pimgd The code is correct, it is just a terrible terrible practice. In my mind this question is review-able. \$\endgroup\$ – konijn Aug 3 '16 at 17:29
  • \$\begingroup\$ @konijn The main problem is that, every time a script element is placed into the page, the JavaScript will be added, right? If I could get around that, by perhaps not replacing script elements, would it still be terrible practice? If so, why? \$\endgroup\$ – Jonah Aug 3 '16 at 20:42
  • \$\begingroup\$ @konijn The question got re-opened. Feel free to tell us how terrible this practice is in an answer :-) \$\endgroup\$ – Mast Aug 4 '16 at 17:55
3
\$\begingroup\$

It will work, but consider why you might be doing SPA's:

  • 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
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.