Module Loader Web Control
Web Component can bridge the gap between declarative and programatic module implementations. It also simplifies implementation by enriching a standard tag with further functionality:
The implementation supports developping modules in the template element inline code that can simply extracted into an extra file to be loaded on demand.
- The URL attribute on the tag specify the url to the resources to be loaded.
- The autoLoad attribute specifies wether the template should be loaded automatically after the page was activated
- the
load()
function allows loading the template on demand - the
start()
function allows starting the template implementation on demand
Both functions work with promises so you can trigger a start()
and the module will be
loaded and started after availability. A parameter can be passed.
Problems and Solution with the <template> tag
After having the content available in the browser there is no well-defined way to add this to the template content.
- setting the innerHTML will create all nodes but as defined in innerHTML behavior will not start the scripts. This is ok as at this stage we don't want script to be executed but cloning the content also doesn't activate the script.
- setting the innerText doesn't create child elements as required.
- using createContextualFragment(txt) will directly trigger the script in the load phase that is unwanted not not behaving as a standard template.
Using innerHTML seems to be near to the standard behavior where html and script is available in the template content but not yet activated. However using innerHTML will be banned for security reasons in some cases so innterText is used here and JavaScript is activated in the moment we clone the content into the target place.
Playgroud
Using template based module is declared using the following HTML code:
<template is="template-loader" id="card" autoLoad="false" url="./13card.htm"></template>
Have a look into the Template Loader implementation in the file templateloader.js.
To use a template with deferred loading just call:
const cardModule = document.querySelector('template#card');
cardModule.load();
cardModule.start('#insert-here', { title: 'Hello', message: (new Date()).toISOString() });
Calling the load() function is optional as the start() function will take care of loading in case the template has not been loaded yet.
The start() function accepts a marker where the template should be used in the document and a optional parameter with data.