Rendering Templates from Strings
The simplest way to use EJS in the browser is to define your template as a string and call ejs.render(). No server, no file system needed.
<script src="https://cdn.jsdelivr.net/npm/ejs/ejs.min.js"></script>
<script>
var template = "<h1><%= title %></h1><p><%= message %></p>";
var html = ejs.render(template, {
title: "Welcome",
message: "This is rendered in the browser."
});
document.body.innerHTML = html;
</script>
This approach works well for small components or when you need quick prototyping without backend setup.
Loading Templates via Fetch
In larger projects, you'll want to load templates from separate files. Use the Fetch API to grab them at runtime.
<script src="https://cdn.jsdelivr.net/npm/ejs/ejs.min.js"></script>
<script>
async function loadAndRender(url, data) {
var response = await fetch(url);
var template = await response.text();
return ejs.render(template, data);
}
loadAndRender("/templates/greeting.ejs", { name: "Visitor" })
.then(function(html) {
document.getElementById("app").innerHTML = html;
});
</script>
Fetch keeps your templates organized in separate files while your JavaScript stays clean and modular.
Using XMLHttpRequest
If you need to support older browsers, XMLHttpRequest works just as well for loading templates.
<script src="https://cdn.jsdelivr.net/npm/ejs/ejs.min.js"></script>
<script>
function loadTemplate(path, data, callback) {
var xhr = new XMLHttpRequest();
xhr.open("GET", path, true);
xhr.onreadystatechange = function() {
if (xhr.readyState === 4 && xhr.status === 200) {
var html = ejs.render(xhr.responseText, data);
callback(html);
}
};
xhr.send();
}
loadTemplate("/templates/card.ejs", { title: "Card" }, function(html) {
document.getElementById("output").innerHTML = html;
});
</script>
It's more verbose than Fetch, but it gives you fine-grained control over the request lifecycle.
Template Caching in the Browser
Loading the same template repeatedly is wasteful. Cache compiled templates so they only parse once.
<script src="https://cdn.jsdelivr.net/npm/ejs/ejs.min.js"></script>
<script>
var cache = {};
function getTemplate(url) {
if (cache[url]) return Promise.resolve(cache[url]);
return fetch(url)
.then(function(r) { return r.text(); })
.then(function(src) {
cache[url] = ejs.compile(src);
return cache[url];
});
}
getTemplate("/templates/item.ejs").then(function(render) {
var html = render({ name: "Widget", price: 9.99 });
document.getElementById("app").innerHTML = html;
});
</script>
Use ejs.compile() instead of ejs.render() to create a reusable function. Store it in a cache object so subsequent calls are instant.