Search code examples
javascriptajaxhtmlhtml5-history

Is there any way to quickly and easily convert standard website loading to AJAX on entire website?


Maybe that's not a good question but I'm wondering if it would be somehow easily and quickly (with just 1 function perhaps?) possible to change ALL links on website from refreshing webpage to loading the URL that user clicked via AJAX?

My website has standard links everywhere but if you want to have mobile application for iPhone out of it you need to use AJAX everywhere (and perhaps HTML5 History API) because any link will open Safari browser.

Do you think there's any way to quickly convert every single link to delete current source code and load brand-new page without refreshing browser window? Or does it require manual coding and separate functions for every single set of links?

Example:

jQuery(document).on('a', 'click', function(){
// STEP1: AJAX call that will make PHP download page from link
// STEP2: Delete current source code and load new one (in this case including deletion of this function itself)
});

Do you think it would be possible or are there any pitfalls here?


Solution

  • I've done something similar to this. It's possible, but you may have to change a couple of things on server side. In my case, i had some links with href = #, some of them had click triggers, so i wanted to keep them out.

    In this function i check every link without href = #, and if they don't have a click event, i bind ajax.

    bindAjaxLinks: function() {
       $('a[href!="#"]').each(function() {
                var eventObj = $(this).data('events');
                if (!eventObj || !eventObj.click) {
                    // not a javascript link, do your thing
                    var link = $(this).attr('href');
                    if (link) {
                        $(this).click(function(event) {
                            event.preventDefault();
                            // do your ajax calling here.
                        });
                    }
                }
        });
    

    Some considerations: In my case, i added an extra parameter, something like isAjax to every request i made with this function, and in backend i sent only a part of whole page(without head and some other markup). And later i replaced what is visible to user with this new html.

    This caused a problem: if server responded with a redirect, i got the whole page, which i didn't want, so i made sure this isAjax parameter is kept after redirects, and that solved this problem.