COMisHARD COMisHARD - 3 months ago 13
HTML Question

Load Local HTML Into Div (Chrome Extension)

I'm not using a framework and I want to implement an architecture whereby a single html file holds the skeleton of my layout, and certain other html snippets are loaded into various divs in that layout. The code is all in the same directory location inside my main extension folder /popup/

I want to build a very simple function to load the locally saved html snippets into the div elements. Here is my first attempt:

function loadView(viewName,destination){
var URL = "/popup/"+viewName;
var client = new XMLHttpRequest();
client.open('GET', URL, false);
client.onreadystatechange = function() {
document.getElementById(destination).innerHTML = client.responseText;
}
client.send();
}

// Example of a call

loadView('contact.html','widgetBox');


Obviously this is terrible because it relies on setting the ajax to asynch false. But under this solution, that is necessary because the next line of code in the script may/does try to manipulate the newly loaded content.

What would be a method for reaching a similar result, that does not depend on ajax? (or at least, which would resolve the need to use asynch false)

Notes:


  • I know that there are frameworks for basically this exact problem. I like to learn how to do things without frameworks. I am not challenging the use of frameworks, I'm just not interested in those approaches in this question. Relatedly, I'd like to avoid using jquery (and as this is a chrome extension, developing in clean JS isn't particularly painful).

  • The content of contact.html is some html, is just a string of html, (i.e. it does not have a header or any content besides that which I seek to load). I am open to another convention besides discrete .html files, but I like this convention as it is easy to keep my various page chunks organized, and keeping them as .html files allows me to read them easily in things that format html nicely.


Answer

You should have your loadView function accept a callback as a third parameter. Then, call it when the Ajax call completes. That way, you can use an async request.

function loadView(viewName, destination, callback){
    var URL = "/popup/"+viewName;
    var client = new XMLHttpRequest();
    client.open('GET', URL);
    client.onreadystatechange = function() {
        if (client.readyState < 4) return; // Wait until the request completes
        document.getElementById(destination).innerHTML = client.responseText;
        callback();
    }
    client.send();  
}

// Example of a call

loadView('contact.html', 'widgetBox', function() {
    // Do whatever comes next
});
Comments