Module Loader Web Control

Excerpt

Loading modules in templates can even be done in a effective way using a Web Component implementation.

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.

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.

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.

See Also

Tags

JavaScript