Search code examples
javascriptfunctionexecute

Understanding how to execute Javascript functions in a certain order


I am creating a framework that allows me to start with a normal static website then if the user has Javascript enabled transforms it into a single page site that pulls in sections from the static pages as the user navigates the site.

I'm still working on the ideas but I'm struggling understanding how to execute Javascript functions in a certain order my code (edited) looks a like this:

EDIT My code in more detail:

When the loadSiteMap() function completes the variable siteMap looks like this:

{ 
    "pageData" : [
        {   
            "loadInTo"      :   "#aboutUs",
            "url"           :   "aboutUs.html",
            "urlSection"    :   ".sectionInner"
        },
        {   
            "loadInTo"      :   "#whatWeDo",
            "url"           :   "whatWeDo.html",
            "urlSection"    :   ".sectionInner" 
        },
        {   
            "loadInTo"      :   "#ourValues",
            "url"           :   "ourValues.html",
            "urlSection"    :   ".sectionInner" 
        },
        {   
            "loadInTo"      :   "#ourExpertise",
            "url"           :   "ourExpertise.html",
            "urlSection"    :   ".sectionInner" 
        }   
    ]
}

The rest of my code:

function loadSiteMap() {
    $('#body').empty();

    $.ajaxSetup({cache : false});

    $.ajax({
        url: 'js/siteMap.js',
        async: false,
        dataType: 'json'

    })
    .done(function(data){
        siteMap = data;
    })
    .fail(function(jqXHR, status){
        alert('Its all gone to shit');
    }); 
}

loadSiteMap();//So this is the first to be executed     



$(function(){
    function loadDataFromSiteMap() {

        var toAppend = '';
        var markerID = 'mark-end-of-append' + (new Date).getTime();
        var loadGraphic = '<img src="images/loadGraphic.gif" alt="loading..." class="loadGraphic" />'

        for(var i=0; i<siteMap.pageData.length; i++) {
            var loader = siteMap.pageData[i];
            toAppend += '<div id="'+ loader.loadInTo.substr(1) +'" class="sectionOuter">'+ loadGraphic +'</div>';
        }

        toAppend += '<div id="' + markerID + '"></div>';

        $('#body').append(toAppend);

        var poller = window.setInterval(function(){

            var detected = document.getElementById(markerID);

            if(detected){
                window.clearInterval(poller);
                $(detected).remove();

                for(var i=0; i<siteMap.pageData.length; i++){
                    var loader = siteMap.pageData[i];

                    var dfd = $.ajax({
                        url: loader.url,
                        async: false
                    });

                    dfd.done(function(data, status, jqXHR){
                        var sections = $(data).find(loader.urlSection);

                        $(loader.loadInTo).html(sections).filter(loader.urlSection);
                    });

                    dfd.fail(function(jqXHR, status){
                        alert('Its all gone to shit');
                    }); 
                }
            }
        }, 100);

    }



    function buildCarousel() {
        $('.sectionInner').each(function(i) {
            if($(this).has('.carousel').length) {
                $(this).append('<a href="#" class="prev">Prev</a><a href="#" class="next">Next</a>');
                $('.prev,.next').fadeIn('slow');
            }
        });
    };


    loadDataFromSiteMap();//This runs second then I want to execute...
    buildCarousel();//Then when this is complete execute...
    anotherFunction();//and so on...

Hopefully from this you can see what I am trying to achieve in terms of executing functions in order. I would like to eventually turn this concept into a jQuery plugin so I can share it. If that has any bearing on what I am trying to achieve now I welcome thoughts.

Many thanks in advance.


Solution

  • I think AJAX is one of the only times you'll have to worry about functions not running in a certain order in JavaScript.

    The trick to asynchronous function calls like AJAX is to make use of callbacks. Put everything in the "Doc ready" section into another callable function (or just an anonymous function in the AJAX complete code), then call this function only when your AJAX call completes. The reason being that the rest of your program will go on executing while the AJAX call is being processed, so callbacks insure the AJAX call is done before continuing what you want to execute next.

    If any of these other functions are asynchronous then you'll have to similarly make a callback on completion that will continue executing the rest of the functions.

    As it stands, though, I see no reason every function but the AJAX one should not be called in order. At least, not without knowing how those functions work.

    Edit: A code example of a callback:

    $.ajax({
      url: 'ajax/test.html',
      success: function(data) {
        //Set sitemap
        (function() {
          //Make the calls to your list of functions
        })(); //<- Execute function right away
      }
    });
    

    Also, according to here, async: false will not work on 'Cross-domain requests and dataType: "jsonp" requests', so if you're calling a different domain or using jsonp that might be the problem.