Defer Loading with Templates
Lifecycle in Web Applications
In typical web applications and web sites you often can find functionality that is not required during the first impression:
Load and activate everything on loading an application is a anti-pattern web applications especially the bigger ones or the ones used by mobile devices.
Loading parts of the application that is only required in rare cases at a later time is a reasonable solution.
Loading application parts that have a high probability of beeing used is another pattern to be implemented.
Loading Functionality
Many web frameworks convert HTML and CSS into Javascript and use the integration pattern of adding
<script>
tags dynamically. This additional JavaScript code is providing
entry point functions that can be used. This also allows pre-loading of modules
and separating the loading phase from the activation.
As we have seen in The Template Element the browser supports storing content that is not yet part of the document and fits good into deferred loading procedure as loading can be done without effecting any other ongoing scripts.
A loading function looks like:
// load template tName from URL
function loadTemplate(tName) {
const p = new Promise((resolve, _reject) => {
const templ = document.querySelector(tName);
const url = templ.getAttribute('url');
fetch(url)
.then(r => r.text())
.then(txt => {
templ.innerHTML = txt;
resolve();
});
});
return (p);
}
Example
The simple example from 07 The Template Element is reused for this but the template element is now having a url instead of innerHTML:
<template id="card" url="./13card.htm"></template>
Loading starts in this example by the DOMContentLoaded event that is calling the loadTemplate()
function:
document.addEventListener('DOMContentLoaded', _e => {
const p = loadTemplate('#card');
p.then(_e => { console.info("templ:", "loaded."); });
});
Now everything is ready and the Activation Button will work.
Summary
Loading parts of an application can be deferred without effecting the page. What's next ?