Are you using Vue, React, Angular, or Svelte to create web apps? I am, and if you are too, I bet it's been a while since you've written an app that renders content without these fine tools.
Armed with only what comes with the browser. Years ago, this is exactly how many of us wrote web apps. While today's tools help abstract that away (and add a bunch of other benefits), it is still useful to know what is happening under the covers.
Also, consider that if you are rendering small amounts of content, you may want to use HTML, JavaScript, and the DOM without any other tools. Recently I wrote some web fundamentals examples to help teach the DOM, HTML, JavaScript, and the basics of the browser. This experience made me realize that maybe other developers, maybe you, would appreciate a reminder of how you can render content without libraries.
If anything, it's fun, educational, and might make us all respect the value of modern libraries and frameworks which handle this for us.
With that, let's explore a few different ways you can render content. Oh, and keep those MDN Web docs handy!
The Sample App
Here is the app I'll demonstrate in this article. It fetches a list of heroes and renders them when you click the button. It also renders a progress indicator while it is fetching.
Tools
The right tools are important, and in this exercise, we want to render some content to the browser using the essential tools that we all have. No frameworks. No libraries. No problem.
All we get to use are HTML, TypeScript/JavaScript, CSS, and the browser DOM (document object model). Now let's get to work and see how we can render HTML.
You can learn more about TypeScript coding with VS Code here
If you look closely, you may see I'm using TypeScript in the code. I'm using it because it is super helpful at avoiding bugs due to its typings, and I get to take advantage of how it transpiles to any JavaScript format I need. You could 100% use JavaScript if you prefer. I'll write more in a future article (soon) about how you can transpile TypeScript too.
The Approach
This sample app renders a list of heroes and a progress indicator (while it is working). Let's start by exploring the simpler of these, the progress indicator, and show various ways in which it renders. Then we'll shift to the list of heroes, and see how things change (or not) when there is more to render.
Rendering Progress Indicators
The progress indicator should appear while the app is determining which heroes to render. So it will not be visible until someone clicks the refresh button, then it will appear, and disappear after the heroes render. Let's explore a few ways this can work.
All of the techniques require some awareness of where to put the elements as they are built. For example, the progress indicator and the heroes list both have to go somewhere. One way to do this is to reference an existing element that will contain them. Another way is to reference an element and replace that element with the new content. We'll see a little of each throughout this article.
Rendering Progress with Inner HTML
Creating HTML and put it inside of another element is one of the oldest techniques, but hey, it works! You locate the element where the progress indicator will go. Then set it's innerHtml
property to the new content. Notice we're also trying to make it readable using template strings that allow it to span multiple lines.
const heroPlaceholder = document.querySelector('.hero-list');
heroPlaceholder.innerHTML = `
<progress
class="hero-list progress is-medium is-info" max="100"
></progress>
`;
Simple. Easy. Why isn't all code like this? I mean, come on, look at how quick this code solves the problem!
Alright, you're probably already thinking ahead at how fragile this code can be. One mistake in the HTML, and bam! We have a problem. And is it genuinely readable? This code is arguably readable, but what happens when the HTML becomes more complex, and you have 20 lines of HTML and classes and attributes, and values and ... you get the point. Yeah, this is not ideal. But for short bits of HTML, it does work, and I wouldn't cast it aside too quickly for one-liners.
Something else to consider is how embedded content might add to the readability and stability of the code. For example, if you add content inside of the progress bar for a loading message that changes, you could do this using the replacement technique like this ${message}
. This isn't good or bad; it just adds to your considerations when creating large template strings.
One last point on innerHTML
is that performance in rendering "may" be a concern. I say this because I do not subscribe to over-optimization. But it is worth testing the performance of rendering HTML using innerHTML
as it can cause rendering and layout cycles in the browser. So keep an eye on it.
Rendering Progress with the DOM API
One way to reduce some of the clutter of the long strings is to use the DOM API. Here you create an element, add any classes it needs, add attributes, set values, and then add it to the DOM.
const heroPlaceholder = document.querySelector('.hero-list');
const progressEl = document.createElement('progress');
progressEl.classList.add('hero-list', 'progress', 'is-medium', 'is-info');
const maxAttr = document.createAttribute('max');
maxAttr.value = '100';
progressEl.setAttributeNode(maxAttr);
heroPlaceholder.replaceWith(progressEl);
The upside here is that the code has more typing, and it relies on the API. In other words, if something was typed incorrectly, the chances are greater in this code than that of the innerHTML
technique that an error will be thrown that will help lead to the problem and solution.
The downside here is that it took six lines of code to render what took one line with innerHTML
.
Is the DOM API code more readable than the innerHTML
technique to render the progress bar? I argue that it is not. But is that because this progress bar HTML is super short and simple? Maybe. If the HTML were 20 lines, the innerHTML
would be less easy to read ... but so would the DOM API code.
Rendering Progress with Templates
Another technique is to create a <template>
tag and use that to make it easier to render content.
Start by creating a <template>
and giving it an id
. The template will not render in the HTML page, but you can reference its contents and use those later. This is very useful so you can write the HTML where it makes the most sense: in the HTML page with all the helpful features of an HTML editor.
<template id="progress-template">
<progress class="hero-list progress is-medium is-info" max="100"></progress>
</template>
Then the code can grab the template using the document.importNode()
method of the DOM API. It can manipulate the content in the template if needed (in this case, there is no need). Then add that content to the DOM to render the progress bar.
const heroPlaceholder = document.querySelector('.hero-list');
const template = document.getElementById('progress-template') as HTMLTemplateElement;
const fetchingNode = document.importNode(template.content, true);
heroPlaceholder.replaceWith(fetchingNode);
Templates are a powerful way to build HTML. I like this technique because it lets you write HTML where it makes sense, and the TypeScript/JavaScript code is doing less.
You might wonder if you can import templates from other files. The answer is that you can, but using other libraries. But this exercise is sticking with no libraries. Natively there has been a discussion about HTML imports for years, but as you can see in the "Can I Use" site, the support is not quite there yet in most modern browsers.
Render a List of Heroes
Let's shift to how we can render the list of heroes using those same three techniques. The differences here from rendering a single <progress>
HTML element and rendering a list of heroes are that we are now rendering:
- multiple HTML elements
- adding multiple classes
- adding child elements, a specific sequence
- rendering a lot of similar content, for each hero
- displaying dynamic text inside of elements
Render Heroes with Inner HTML
Using innerHTML
it makes sense to first start with the array of heroes and iterate through them for each hero. This will help build each row, one at a time. The rows are identical other than the hero's name and description, which we can insert using template strings. Each hero in the array builds up a <li>
, which maps to a rows
array. Finally, the rows array transform into the raw HTML, wrapped with a <ul>
, and set to the innerHTML
.
function createListWithInnerHTML(heroes: Hero[]) {
const rows = heroes.map(hero => {
return `<li>
<div class="card">
<div class="card-content">
<div class="content">
<div class="name">${hero.name}</div>
<div class="description">${hero.description}</div>
</div>
</div>
</div>
</li>`;
});
const html = `<ul>${rows.join()}</ul>`;
heroPlaceholder.innerHTML = html;
Again, this works. And it is "arguably" quite readable. Is it the most performant? Is it ripe with possible typing mistakes that won't be caught easily (or ever)? You be the judge. Let's hold judgment until we see some other techniques.
Rendering Heroes with the DOM API
function createListWithDOMAPI(heroes: Hero[]) {
const ul = document.createElement('ul');
ul.classList.add('list', 'hero-list');
heroes.forEach(hero => {
const li = document.createElement('li');
const card = document.createElement('div');
card.classList.add('card');
li.appendChild(card);
const cardContent = document.createElement('div');
cardContent.classList.add('card-content');
card.appendChild(cardContent);
const content = document.createElement('div');
content.classList.add('content');
cardContent.appendChild(content);
const name = document.createElement('div');
name.classList.add('name');
name.textContent = hero.name;
cardContent.appendChild(name);
const description = document.createElement('div');
description.classList.add('description');
description.textContent = hero.description;
cardContent.appendChild(description);
ul.appendChild(li);
});
heroPlaceholder.replaceWith(ul);
}
Rendering Heroes with Templates
The heroes list can be rendered using templates, using the same technique we used to render the <progress>
element. First, the template is created in the HTML page. This HTML is slightly more complicated than what we saw with the <progress>
element. You can easily imagine how even more HTML would not be a problem using this technique. It's just HTML in an HTML page, with all the benefits of fixing errors and formatting with a great editor like VS Code.
<template id="hero-template">
<li>
<div class="card">
<div class="card-content">
<div class="content">
<div class="name"></div>
<div class="description"></div>
</div>
</div>
</div>
</li>
</template>
You could then write the code to create the heroes list by first creating the <ul>
to wrap the heroes <li>
rows. Then you can iterate through the heroes
array and grab the same template for each hero, using the document.importNode()
method once again. Notice the template can be used repeatedly to create each row. One template becomes the blueprint for as many here rows as you need.
The heroes list should show each respective hero's name and description. This means that the template only gets you so far, then you have to replace the hero specific values inside of the template. This is where it makes sense to have some way to identify and reference the places where you will put those hero specific values. In this example, the code uses the querySelector('your-selector')
method to get a reference for each hero, before setting the name and description.
function createListWithTemplate(heroes: Hero[]) {
const ul = document.createElement('ul');
ul.classList.add('list', 'hero-list');
const template = document.getElementById('hero-template') as HTMLTemplateElement;
heroes.forEach((hero: Hero) => {
const heroCard = document.importNode(template.content, true);
heroCard.querySelector('.description').textContent = hero.description;
heroCard.querySelector('.name').textContent = hero.name;
ul.appendChild(heroCard);
});
heroPlaceholder.replaceWith(ul);
}
Is the template easier than the other techniques? I think "easy" is relative. I feel that this code follows a pattern that is reasonably repeatable, readable, and less error-prone than the other techniques.
Summary
Notice I have not mentioned how the major frameworks and libraries handle rendering content. Vue, React, Angular, and Svelte all make this significantly easier using less code. They also have their respective additional benefits beyond rendering. This article is only focusing on a relatively simple rendering using the DOM with pure HTML and TypeScript/JavaScript.
Where does this leave us?
Hopefully, this gives you an idea of how you can render content without any libraries. are there other ways? Absolutely. Can you make reusable functions to make the code more straightforward and more reusable? Absolutely. But at some point, you may want to try one of the very excellent framework tools such as Vue, React, Angular, or Svelte.
These popular frameworks are doing a lot for us. If you are like me, you recall using pure DOM code with JavaScript or jQuery to render content. Or you remember using tools like handlebars or mustache to render content. Or maybe you've never rendered to the DOM without a framework. You can imagine what today's libraries and frameworks are doing under the covers to render content for you.
It's helpful to know what can be done with pure HTML, TypeScript/JavaScript, and CSS even if you are using a framework that abstracts this from you.
Whatever your experience, I hope it was helpful to take a brief exploration through some of the techniques that you can use to render content.