Load HTML once with AJAX

While working on a project recently, a dynamically loaded section was needed. It was used in a transition between step one and two in the user’s journey, after an API call had been made. The user was allowed to go back to step one at any time, resulting in a new API call – which was to be expected – but the call to get the HTML for step two was also made again. The same HTML which had just been loaded the first time around.

To fix this we wrapped the call to get the HTML, between step one and two, in a method to get the HTML and provided a callback once it was finished. The reason a callback was needed is due the asynchronous nature of AJAX, you couldn’t rely on it being done by the next call down in the code. This poses a problem though, if on the 1st call it is async and could take a few milliseconds to complete but on the second time around it’s already there in a variable, you have to wait for one and not another. The callback gets around this.

View Demo

The jQuery Function#

Get getHtml function below is what manages most of the calls and uses a global variable (not always advised) to check if it’s been done before.

var globalHtml = null;

function getHtml(callback) {
    if (globalHtml === null) {
        var req = $.get('to-load.html');
        req.done(function(html) {
            globalHtml = html;
            callback(html);
        });
    }
    else {
        callback(globalHtml);
    }
}

Usage#

function doSomething(html) {
    // do something with the html
}

getHtml(doSomething);

View Demo

This is probably just one way to fix the same problem, there might be a more efficient way or elegant way. Let us know in the comments if you think you have a better solution.